Python's threading
module offers two crucial synchronization tools: Lock
and RLock
, both designed to control access to shared resources in multithreaded applications. However, their functionalities differ significantly.
Lock
(threading.Lock)Lock
Example:<code class="language-python">import threading lock = threading.Lock() def critical_section(): lock.acquire() try: print(f"{threading.current_thread().name} is accessing the shared resource.") finally: lock.release() thread1 = threading.Thread(target=critical_section) thread2 = threading.Thread(target=critical_section) thread1.start() thread2.start() thread1.join() thread2.join()</code>
RLock
(threading.RLock)RLock
Example:<code class="language-python">import threading rlock = threading.RLock() def recursive_task(count): rlock.acquire() try: print(f"{threading.current_thread().name} acquired the lock; count = {count}") if count > 0: recursive_task(count - 1) # Recursive call; re-acquires the lock finally: rlock.release() thread = threading.Thread(target=recursive_task, args=(3,)) thread.start() thread.join()</code>
Lock
vs. RLock
Feature |
|
(threading.RLock) |
||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Reentrancy | Non-reentrant | Reentrant | ||||||||||||
Use Case | Simple locking | Recursive/nested locking | ||||||||||||
Performance | Generally faster | Slightly more overhead |
Lock
Choosing Between RLock
and Lock
Prefer RLock
Opt for The above is the detailed content of R-Lock vs Lock in Python. For more information, please follow other related articles on the PHP Chinese website!