为了保证多线程任务执行时,共享资源的同步,出现了锁这个东西。
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()

Mr布
31 声望0 粉丝

There is no time limit,start whenever you want. Remember YOU ARE A RUNNER.