標籤:線程 lock 通知 tar 進程 first bsp 指定 lease
cond = threading.Condition()
# 類似lock.acquire()
cond.acquire()
# 類似lock.release()
cond.release()
# 等待指定觸發,同時會釋放對鎖的擷取,直到被notify才重新佔有瑣。
cond.wait()
# 發送指定,觸發執行
cond.notify()
import threading,timecond = threading.Condition()#cond.acquire()#cond.release()#cond.wait()#cond.notify()def aa(): print (‘thread_aa get‘) cond.acquire() time.sleep(5) print (‘thread_aa finished first job‘) cond.wait()#釋放對鎖的控制,好讓別的進程acquire到 #同時阻塞在此,等待得到鎖的那個進程的先cond.notify後(cond.wait或cond.release) print (‘thread_aa get again‘) time.sleep(5) print (‘thread_aa finished all work‘) cond.notify()#告訴剛才釋放鎖的那個進程等通知吧,等我要麼wait要麼release cond.release()#釋放鎖def bb(): cond.acquire() print (‘thread_bb get‘) cond.notify()#告訴剛才釋放鎖的那個進程等通知吧,等我要麼wait要麼release print (‘依然是我bb在運行‘) time.sleep(5) print (‘thread_bb finished first job‘) cond.wait()#釋放對鎖的控制,而後被阻塞的aa就可以執行了 #同時阻塞在此,等待得到鎖的aa的先cond.notify後(cond.wait或cond.release) print (‘thread_aa get again‘) print (‘thread_bb finished all works‘) cond.release() a=threading.Thread(target=aa)a.start()time.sleep(2)b=threading.Thread(target=bb)b.start()
python線程之condition