有没有办法创建对象并使用它们而不是在主线程中?我已阅读this link,但不了解如何将其应用于我的示例(见下文)。
import threading
from gi.repository import Gtk, Gdk, GObject, GLib
class Foo:
def bar(self):
pass
class ListeningThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.cls_in_thread = None
def foo(self, _):
self.cls_in_thread = Foo()
print(threading.current_thread())
print('Instance created')
def bar(self, _):
self.cls_in_thread.bar()
print(threading.current_thread())
print('Instance method called')
def run(self):
print(threading.current_thread())
def main_quit(_):
Gtk.main_quit()
if __name__ == '__main__':
GObject.threads_init()
window = Gtk.Window()
box = Gtk.Box(spacing=6)
window.add(box)
lt = ListeningThread()
lt.daemon = True
lt.start()
button = Gtk.Button.new_with_label("Create instance in thread")
button.connect("clicked", lt.foo)
button2 = Gtk.Button.new_with_label("Call instance method in thread")
button2.connect("clicked", lt.bar)
box.pack_start(button, True, True, 0)
box.pack_start(button2, True, True, 0)
window.show_all()
window.connect('destroy', main_quit)
print(threading.current_thread())
Gtk.main()
这里更准确的是我现在得到的输出:
<ListeningThread(Thread-1, started daemon 28268)>
<_MainThread(MainThread, started 23644)>
<_MainThread(MainThread, started 23644)>
Instance created
<_MainThread(MainThread, started 23644)>
Instance method called
我希望它有点像这样:
<ListeningThread(Thread-1, started daemon 28268)>
<_MainThread(MainThread, started 23644)>
<ListeningThread(Thread-1, started daemon 28268)>
Instance created
<ListeningThread(Thread-1, started daemon 28268)>
Instance method called
此外,我想确保cls_in_thread
存在于同一个帖子中(在我找到threading.local()
的文档中,但我不确定它是否存在需要)。有没有办法实现这种行为?
答案 0 :(得分:0)
以下是一种方法示例:pithos/gobject_worker.py
在另一个线程上有一个你想要的作业队列,然后在作业完成后在主线程上调用你的回调。
还要意识到你不应该从另一个线程修改主线程上的对象。