简体   繁体   English

GTK3 python 中的线程

[英]Threading in GTK3 python

I'm building a GTK GUI in Python and I need to get some data from the database which takes quite long, so the GUI freezes.我正在 Python 中构建一个 GTK GUI,我需要从数据库中获取一些需要很长时间的数据,因此 GUI 冻结。

So I'm now using Threads to run the refreshing "in the background":所以我现在使用线程在“后台”运行刷新:

Thread(target=self.updateOrderList).start()

I have GUI class with alle relevant methods to manipulate the GUI.我有 GUI class 和所有相关的方法来操作 GUI。 My solution work 80% of the time, but when it doesn't GTK crashed and it outputs this:我的解决方案在 80% 的时间里都能正常工作,但是当它不工作时 GTK 崩溃并输出:

[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python3.6: ../../src/xcb_io.c:165: dequeue_pending_request:

The other times it works good, the data get loaded and its refreshing the gui.其他时候效果很好,数据被加载并刷新了 gui。

edit: Sometimes I get this error:编辑:有时我会收到此错误:

Gdk-Message: 11:13:42.848: main.py: Fatal IO error 11 (Die Ressource ist zur Zeit nicht verfügbar) on X server :0

Sometimes I click the refresh button several times and it works, but then it doesn't at some point.有时我多次单击刷新按钮并且它可以工作,但有时它不会。

My main.py looks like this:我的 main.py 看起来像这样:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject

import gui

GObject.threads_init()

# start gui
gui.Gui()
Gtk.main()

Any ideas whats happening here?有什么想法吗?

Markus马库斯

Okay, GTK3 is not threadsafe.好吧,GTK3 不是线程安全的。 So I changed the program logic - doing requests in a new thread, and handling the GUI manipulation in the GUI thread ONLY .所以我改变了程序逻辑——在一个新线程中执行请求,并且在 GUI 线程中处理 GUI 操作。 So that means I have to emit a "requests done" signal to the event loop:所以这意味着我必须向事件循环发出“请求完成”信号:

Creating a new signal and registering it:创建一个新信号并注册它:

GObject.signal_new("my-custom-signal", self.window, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,
                       (GObject.TYPE_PYOBJECT,))
self.window.connect("my-custom-signal", self.updateOrderListCallback)

So when I click a button, start a thread:所以当我点击一个按钮时,启动一个线程:

Thread(target=self.updateOrderListThread).start()

In that thread, do the calculations, and then emit the signal:在那个线程中,进行计算,然后发出信号:

self.window.emit("my-custom-signal", None)

so than the callback will be called after the calculations/requests/whatever are done and it works!因此,在计算/请求/完成任何操作之后将调用回调并且它可以工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM