GObject信号和GLib MainLoop

时间:2019-02-07 09:29:59

标签: glib gobject

我有一个GObject派生的对象,该对象在某个线程中发出信号,我想在运行GLib的{​​{1}}的主线程中处理它们。这是使用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内部主线程中的信号?

1 个答案:

答案 0 :(得分:1)

从您的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 …