为了保证多线程使命实行时,共享资源的同步,涌现了锁这个东西。
Lock是壅塞其他线程对共享资源的接见,且统一线程只能acquire一次,如多于一次就涌现了死锁,顺序没法继承实行。
为了保证线程对共享资源的独有,又防止死锁的涌现,就有了RLock。RLock许可在统一线程中被屡次acquire,线程对共享资源的开释须要把一切锁都release。即n次acquire,须要n次release。
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()