Mutex — Explained with Examples
A mutex (mutual exclusion) is a synchronization primitive that prevents multiple threads from accessing a shared resource simultaneously.
A mutex provides exclusive access to a shared resource. A thread locks the mutex before entering a critical section and unlocks it after leaving. If another thread tries to lock an already-locked mutex, it blocks until the mutex is unlocked. Mutexes can be recursive (same thread can lock multiple times) or non-recursive. Failure to unlock causes deadlocks.
Think of a mutex like a bathroom key at a gas station. Only one person can hold the key at a time. If someone is inside (locked), you wait outside until they exit and return the key (unlock). Without the key system, two people might try to use the bathroom simultaneously — chaos.
Mutexes protect shared data from race conditions but introduce contention that can reduce performance. Fine-grained locking (many small mutexes) reduces contention but increases complexity.
import threading
class Counter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()
def increment(self):
with self.lock: # Acquire lock automatically
current = self.value
# Simulate some work
self.value = current + 1
def get_value(self):
with self.lock:
return self.value
counter = Counter()
threads = []
for _ in range(100):
t = threading.Thread(target=counter.increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"Final value: {counter.get_value()}") # Always 100Always hold mutexes for the shortest possible duration and avoid nested locks to prevent deadlocks. Use with statements (Python) or RAII (C++) for automatic unlocking.
Semaphore, Deadlock, Critical Section, Race Condition, Thread Safety
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro