【发布时间】:2011-03-15 22:52:04
【问题描述】:
我有一些带有 2 个线程的 python 应用程序。每个线程都在一个单独的 gui 中运行。 GUI 需要独立运行而不会阻塞。我想弄清楚如何让 thread_1 触发在 thread_2 中发生的事件?
下面是一些我希望函数 foo 以最简单、最优雅的方式尽快触发函数 bar 的代码,而不会消耗不必要的资源。下面是我想出的。
bar_trigger=False #global trigger for function bar.
lock = threading.Lock()
class Thread_2(threading.Thread):
def run(self):
global lock, bar_trigger
while(True):
lock.acquire()
if bar_trigger==True:
Thread_2.bar() #function I want to happen
bar_trigger=False
lock.release()
time.sleep(100) #sleep to preserve resources
#would like to preserve as much resources as possible
# and sleep as little as possible.
def bar(self):
print "Bar!"
class Thread_1(threading.Thread):
def foo(self):
global lock, bar_trigger
lock.acquire()
bar_trigger=True #trigger for bar in thread2
lock.release()
有没有更好的方法来做到这一点?我不是线程专家,因此对于如何从 thread_1 中最好地触发 thread_2 中的方法的任何建议表示赞赏。
【问题讨论】:
-
我不知道任何支持多线程 GUI 编程的 GUI 框架。您使用的是哪个框架?
标签: python multithreading