【问题标题】:GObject signals and GLib MainLoopGObject 信号和 GLib MainLoop
【发布时间】:2019-02-07 09:29:59
【问题描述】:

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

【问题讨论】:

    标签: glib gobject


    【解决方案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 …
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多