我只知道多線程的基本概念,而我目前遇到需要一些幫助的情況。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