爲了保證多線程任務執行時,共享資源的同步,出現了鎖這個東西。
Lock是阻塞其餘線程對共享資源的訪問,且同一線程只能acquire一次,如多於一次就出現了死鎖,程序沒法繼續執行。
爲了保證線程對共享資源的獨佔,又避免死鎖的出現,就有了RLock。RLock容許在同一線程中被屢次acquire,線程對共享資源的釋放須要把全部鎖都release。即n次acquire,須要n次release。python
import threading,time,random lock=threading.RLock() result=[] def step1(): global result if lock.acquire(): result.append('step1') time.sleep(2) lock.release() def step2(): global result if lock.acquire(): result.append('step2') time.sleep(2) lock.release() def showresult(): if lock.acquire(): step1() step2() lock.release() print result def clearresult(): global result if lock.acquire(): result=None time.sleep(2) lock.release() print result t1=threading.Thread(target=showresult) t2=threading.Thread(target=clearresult) t1.start() t2.start()