2017-07-27 27 views
0

我很難理解下面的多線程同步代碼,希望有人能指出我誤解的地方。python鎖誤解

import threading 

cond = threading.Condition() 
class user(threading.Thread): 
    def __init__(self, cond,no): 
     threading.Thread.__init__(self) 
     self.cond = cond 
     self.no = no 

    def run(self): 
     self.cond.acquire() 

     print(self.no + '_1') 
     self.cond.notify() 
     self.cond.wait() 

     print(self.no + '_2') 
     self.cond.notify() 
     self.cond.wait() 

     self.cond.release() 


user1 = user(cond,'user1') 
user2 = user(cond,'user2') 
user1.start() 
user2.start() 

運行結果是:

user1_1 
user2_1 
user1_2 
user2_2 

根據我的理解,這兩個線程應該是死鎖的情況,因爲USER1獲得「COND」,並等待user2的在「self.cond通知.wait()',而user2在'self.cond.acquire()'被阻止,無法到達'self.cond.notify()'。看起來他們都被封鎖了,等待另一個人給他們他們需要的東西,所以他們應該處於僵局。

我對鎖的誤解在哪裏?

回答

0

您的程序正常工作。沒有死鎖,因爲Condition.wait()釋放鎖,允許user2獲取它並繼續。