我只知道多线程的基本概念,而我目前遇到需要一些帮助的情况。Python多线程:需要建议使用条件变量同步2个线程
我有两个任务要完成,并且都应该连续执行。事情是,第二个任务应该在第一个线程首先完成一些工作之后才开始。现在两个线程类看起来大致如下所示:
finished = False # shared flag
class first(threading.Thread):
def __init__(self, cond, finished):
threading.Thread.__init__(self)
self.cond = cond
self.finished = finished
def run(self):
self.cond.aquire()
do_something()
self.finished = True #change the flag
self.cond.notify()
self.cond.release()
do_something_else()
class second(threading.Thread):
def __init__(self, cond, finished):
threading.Thread.__init__(self)
self.cond = cond
self.finished = finished
def run(self):
self.cond.aquire()
while self.finished == False:
self.cond.wait()
self.cond.release()
do_something()
然而,事实是,该程序仍执行随机不管等待的()和notify()。有人可以帮我解决这个问题吗?谢谢。
请出示你如何在代码中使用这些类 – 2012-04-02 22:34:41