GObject 信号和 GLib MainLoop
GObject signals and GLib MainLoop
我有一个 GObject
派生的对象,它在某个线程中发出信号,我想在运行 GLib
的 MainLoop
的主线程中处理它们。这是使用 PyGObject
:
的示例代码
import gi
from gi.repository import GObject, GLib
class SomeObj(GObject.Object, threading.Thread):
def __init__(self, device_path, terminate_event):
GObject.Object.__init__(self)
threading.Thread.__init__(self)
def run():
...
self.emit('sig')
...
@GObject.Signal
def sig(self):
pass
def callback(instance):
...
# will be called in obj's thread
loop = GLib.MainLoop()
obj = SomeObj()
self.watcher.connect('sig', callback)
obj.start()
loop.run()
callback()
将在 obj
的线程中调用。如何在 loop.run()
?
内的主线程中处理信号
从您的 callback
信号处理程序将事件推送到主线程的主上下文:
def callback(instance):
# None here means the global default GMainContext, which is running in your main thread
GLib.MainContext.invoke(None, callback_main, instance)
def callback_main(instance):
# Double check that we’re running in the main thread:
assert(GLib.MainContext.is_owner(None))
# … the code you want to be executed in the main thread …
我有一个 GObject
派生的对象,它在某个线程中发出信号,我想在运行 GLib
的 MainLoop
的主线程中处理它们。这是使用 PyGObject
:
import gi
from gi.repository import GObject, GLib
class SomeObj(GObject.Object, threading.Thread):
def __init__(self, device_path, terminate_event):
GObject.Object.__init__(self)
threading.Thread.__init__(self)
def run():
...
self.emit('sig')
...
@GObject.Signal
def sig(self):
pass
def callback(instance):
...
# will be called in obj's thread
loop = GLib.MainLoop()
obj = SomeObj()
self.watcher.connect('sig', callback)
obj.start()
loop.run()
callback()
将在 obj
的线程中调用。如何在 loop.run()
?
从您的 callback
信号处理程序将事件推送到主线程的主上下文:
def callback(instance):
# None here means the global default GMainContext, which is running in your main thread
GLib.MainContext.invoke(None, callback_main, instance)
def callback_main(instance):
# Double check that we’re running in the main thread:
assert(GLib.MainContext.is_owner(None))
# … the code you want to be executed in the main thread …