2013-03-18 130 views
6

我有一個python類讓我們稱之爲AClass和另一個擴展線程的MyThread。在這個AClass中,我創建了MyThread類的2個對象,並且我還有一個信號量,我將它作爲MyThread類的構造函數的參數。我的問題是如果我在一個MyThread對象中修改信號量,另一個MyThread對象會看到差異嗎?例如:Python線程和信號燈

class AClasss: 

    def function: 
      semafor = threading.Semaphore(value=maxconnections) 
      thread1 = Mythread(semafor) 
      thread2 = Mythread(semafor) 
      thread1.start() 
      thread1.join() 
      thread2.start() 
      thread2.join() 

class MyThread(Thread): 
    def __init__(self,semaphore): 
     self.semaphore = semaphore 
    def run(): 
     semaphore.acquire() 
     "Do something here" 
     semaphore.release() 

那麼thread1是否看到thread2所做的信號量更改,反之亦然?

回答

7

這就是信號量的目的,它們允許您安全地同步併發進程。

請記住,Python中的線程不會真的除非您釋放GIL(執行IO,調用庫等),否則會獲得併發性。如果這就是你要做的,你可能需要考慮multiprocessing庫。

+1

非常感謝,我雖然如此,但在編碼前我想確定一下。 – exilonX 2013-03-18 19:56:25