Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

python threading中的lock rlock 为何rlock可以调用多次acquire

在python的多线程中,使用threading中的lock rlock锁, 为何rlock可以调用多次acquire,lock缺不能,lock调用多次而且会发生死锁,rlock不会,求大神指点下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

rlock是可重入锁,你可以简单的理解它自带一个计数器,acquire则计数器+1,release则计数器-1.不可出现负值,否则会跑出异常。

为什么要这么做呢,因为应用场景不同,可重入锁可以调用另外一个需要该锁的方法,而不可重入锁是不能这么做的。

def fun1():
    rlock.acquire()
    fun2()
    rlock.release()

def fun2():
    rlock.acquire()
    rlock.release()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...