The mutex: your first and most important primitive
A mutex (mutual exclusion lock) has two operations: lock() and unlock(). At most one thread holds the mutex at a time; every other caller blocks until it is released. The region between lock and unlock is the critical section.
Correct mutex usage in Python:
import threading
_lock = threading.Lock()
_counter = 0
def safe_increment():
global _counter
with _lock: # acquires on entry, releases on exit — even on exception
_counter += 1
Key rules:
- Always use the same lock for a given piece of shared data. One unprotected access defeats the mutex entirely.
- Prefer RAII / context managers. Manual
lock()/unlock()leaks on exceptions. Python'swith, C++'sstd::lock_guard, Go'sdefer mu.Unlock()all enforce this. - Keep critical sections short. Every nanosecond inside the lock is a nanosecond other threads are blocked.
