what's the difference between Rlock and Lock?
2018-02-28 16:06
543 查看
来自StackOverflow上的问答:
The main difference is that a
Here's an example demostrating why
The main difference is that a
Lockcan 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).An
RLockon 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".Another difference is that an acquired
Lockcan be released by any thread, while an acquired
RLockcan only be released by the thread which acquired it.
Here's an example demostrating why
RLockis useful at times. Suppose you have:
def f(): g() h() def g(): h() do_something1() def h(): do_something2()Let's say all of
f,
g, and
hare public (i.e. can be called directly by an external caller), and all of them require syncronization.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()Basically, since
fcannot call
gafter 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.Using an
RLockelegantly solves the problem:
lock = RLock() def f(): with lock: g() h() def g(): with lock: h() do_something1() def h(): with lock: do_something2()
相关文章推荐
- Whats the difference between git reset --mixed, --soft, and --hard?
- What’s the difference between Taxonomies and Ontologies? - Ask Dr. Search
- What are the difference between DDL, DML and DCL commands[转]
- What Is the Difference Between a Block, a Proc, and a Lambda in Ruby
- What is the difference between Web Farm and Web Garden?
- What are the difference between DDL, DML and DCL commands?
- What is the difference between SVD and matrix factorization in context of recommendation engine?
- What is the difference between Array.Clone and Array.Copy Method
- What is the difference between getWidth/heigth() and getMeasuredWidth/Heigth() in Android SDK?
- whats is the difference between train, validation and test set, in neural networks?
- What is the difference between /dev/ttyUSB and /dev/ttyACM?
- What's the difference between gcc and g++/gcc-c++?
- What is the difference between ++i and i++
- Multi-thread: What is the difference between OpenMP and MPI
- what's the difference between CPU and GPU
- What's the difference between Quartz Core, Core Graphics and Quartz 2D?
- What is the difference between “make” and “make all”?
- C++ Memory Management : What is the difference between malloc/free and new/delete?
- What is the difference between an EXE and a DLL?
- What is the difference between JSP and servlets?