问题描述
从文档:
我不确定我们为什么需要这个?Rlock
和Lock
有什么区别?
I am not sure why do we need this?what's the difference between Rlock
and Lock
?
推荐答案
主要区别在于Lock
只能获取一次.在发布之前,无法再次获取它. (发布后,任何线程都可以重新获取它.)
The main difference is that a Lock
can only be acquired once. It cannot be acquired again, until it is released. (After it's been released, it can be re-acaquired by any thread).
另一方面,同一线程可以多次获取RLock
.它需要被释放相同的次数才能被解锁".
An RLock
on the other hand, can be acquired multiple times, by the same thread. It needs to be released the same number of times in order to be "unlocked".
另一个区别是,获取的Lock
可以由任何线程释放,而获取的RLock
只能由获取它的线程释放.
Another difference is that an acquired Lock
can be released by any thread, while an acquired RLock
can only be released by the thread which acquired it.
这是一个示例,说明了为什么RLock
有时有用的原因.假设您有:
Here's an example demostrating why RLock
is useful at times. Suppose you have:
def f():
g()
h()
def g():
h()
do_something1()
def h():
do_something2()
假设f
,g
和h
都是 public (即可以由外部呼叫者直接调用),并且它们都需要同步.
Let's say all of f
, g
, and h
are public (i.e. can be called directly by an external caller), and all of them require syncronization.
使用Lock
,您可以执行以下操作:
Using a Lock
, you can do something like:
lock = Lock()
def f():
with lock:
_g()
_h()
def g():
with lock:
_g()
def _g():
_h()
do_something1()
def h():
with lock:
_h()
def _h():
do_something2()
基本上,由于f
在获取锁定后无法调用g
,因此需要调用g
的原始"版本(即_g
).因此,您最终获得了每个功能的同步"版本和原始"版本.
Basically, since f
cannot call g
after acquiring the lock, it needs to call a "raw" version of g
(i.e. _g
). So you end up with a "synced" version and a "raw" version of each function.
使用RLock
可以很好地解决该问题:
Using an RLock
elegantly solves the problem:
lock = RLock()
def f():
with lock:
g()
h()
def g():
with lock:
h()
do_something1()
def h():
with lock:
do_something2()
这篇关于Lock和RLock有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!