Intermediate LevelPython
How do you prevent thread race conditions on shared memory using threading.Lock, RLock, and Semaphore?
❓ Interview Prompt: Explain Thread Synchronization, `threading.Lock` (Mutex), `RLock` (Reentrant Lock), `Semaphore`, race conditions, and atomic access.
When multiple threads modify shared mutable memory concurrently, Race Conditions occur! Thread synchronization primitives prevent data corruption:
•
'threading.Lock': Mutual exclusion lock (only 1 thread can hold lock at a time).
•
'threading.RLock': Reentrant lock (can be acquired multiple times by the SAME thread without deadlocking).
•
'threading.Semaphore(value)': Restricts access to a fixed number of concurrent threads.
Code Implementation Example
python
import threading
shared_counter = 0
counter_lock = threading.Lock()
def increment():
global shared_counter
for _ in range(100000):
with counter_lock: # Safely acquire and release mutex lock!
shared_counter += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print('Final Counter:', shared_counter) # Guaranteed 500,000!💡Preventing race conditions using threading.Lock mutex.
🎯 Interview Key Takeaway
Always wrap shared mutable state updates in a threading.Lock context manager to prevent race conditions.
#threading#Lock#Race Condition#Mutex#Intermediate
Back to all Python Questions→