Home >Backend Development >Python Tutorial >R-Lock vs Lock in Python

R-Lock vs Lock in Python

DDD
DDDOriginal
2025-01-24 18:12:10859browse

R-Lock vs Lock in Python

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.


1. Lock (threading.Lock)

  • Mechanism: A basic locking mechanism. Only one thread can hold the lock at any given time. Any other thread attempting acquisition will block until the lock is released.
  • Reentrancy: Non-reentrant. A thread already possessing the lock cannot acquire it again; attempting to do so results in a deadlock.
  • Application: Ideal for situations where a thread needs the lock only once, releasing it upon task completion.

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>

2. RLock (threading.RLock)

  • Mechanism: A reentrant lock, allowing a thread to acquire the same lock multiple times without causing deadlock. Each acquisition requires a corresponding release.
  • Reentrancy: Reentrant. A thread can reacquire the lock it already holds, provided it releases it the same number of times.
  • Application: Suitable for scenarios involving recursive functions or nested lock-protected operations where a thread might need the same lock repeatedly.

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>

Key Differences: Lock vs. RLock

Feature
Feature Lock (threading.Lock) RLock (threading.RLock)
Reentrancy Non-reentrant Reentrant
Use Case Simple locking Recursive/nested locking
Performance Generally faster Slightly more overhead
(threading.Lock)

(threading.RLock)
Reentrancy Non-reentrant Reentrant
Use Case Simple locking Recursive/nested locking
Performance Generally faster Slightly more overhead

LockChoosing Between RLock and

  • LockPrefer
  • for straightforward locking scenarios where reentrancy is unnecessary. It's simpler and often faster.
  • RLockOpt for
  • when dealing with recursive functions or nested locking, preventing potential deadlocks. The added complexity is justified by the prevention of deadlocks in these specific situations.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Race Condition in Python.Next article:Race Condition in Python.