2017-07-27 7 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が「指揮」を取得し、「self.condでUser2の通知を待つため

user1_1 
user2_1 
user1_2 
user2_2 

私の理解によれば、2つのスレッドがデッドロック状態にする必要があります'self.cond.notify()'に到達できません。彼らはすべてブロックされ、他の人が必要なものを与えるのを待っているように見えるので、デッドロック状態にあるはずです。

ロックについての私の誤解はどこですか?

答えて

0

あなたのプログラムは動作するはずです。 Condition.wait()がロックを解除し、user2がロックを取得して処理を続行できるように、デッドロックはありません。