2012-04-02 25 views
0

我只知道多線程的基本概念,而我目前遇到需要一些幫助的情況。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()。有人可以幫我解決這個問題嗎?謝謝。

+0

請出示你如何在代碼中使用這些類 – 2012-04-02 22:34:41

回答

3

class firstself.finished是全球finished的價值,而不是它的一個引用的副本,所以它具有的class secondself.finished沒有活的關係。

您應該可能會創建一個全局的Queue對象(它旨在與threading模塊配合使用)。讓兩個類都引用隊列,並讓第一個線程向隊列寫入超時信號,第二個線程阻塞,直到它讀取超時。

+0

謝謝你的答案羅素! – 2012-04-03 01:30:44

1

您可以完全避免同步。使用3個線程而不是2.

線程1a'做了一些工作'並終止。 線程1b在1a結束時開始,並且 線程2獨立啓動。

(此外,我想你知道,你不能有效地與Python線程共享CPU;這些只是很好的I/O並行等着當你需要CPU密集型的並行化,使用multiprocessing。)