0
有沒有辦法在主線程中創建對象並使用它們?我已閱讀this link,但不明白如何將其應用於我的示例(請參見下文)。PyGObject:如何使用線程中的對象?
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()
,但我不確定是否需要)。有沒有辦法實現這種行爲?