python中的RLock和Lock

为了保证多线程使命实行时,共享资源的同步,涌现了锁这个东西。
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布
    原文地址: https://segmentfault.com/a/1190000000361855
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞