Locks solve race conditions, but they introduce another danger: the deadlock.
What a deadlock is
It happens when two or more threads wait forever for each other. The typical case: thread 1 holds lock A and asks for B; thread 2 holds B and asks for A. Neither gives way, and the program hangs without any error.
| Moment | Thread 1 | Thread 2 |
|---|---|---|
| 1 | acquires A | acquires B |
| 2 | asks for B and waits… | asks for A and waits… |
| 3 | waits forever | waits forever |
Four conditions occur at the same time: mutual exclusion (only one thread holds a lock), hold and wait (more locks are requested without releasing the ones held), no preemption (nobody takes a lock away from another) and circular wait (there is a cycle of threads waiting for each other). If you break one, there is no deadlock.
Prevention 1: a global lock order
The simplest and most reliable technique is to break the circular wait: all threads ask for locks in the same order (for example alphabetical or by number). That way a cycle is impossible.
def locks_in_order(*names):
"""Returns the locks in a fixed global (alphabetical) order."""
return sorted(names)
# Thread 1 wants A and B; thread 2 wants B and A.
print(locks_in_order("A", "B")) # ['A', 'B']
print(locks_in_order("B", "A")) # ['A', 'B'] -> both ask for A first: no cycle
To know whether a set of threads is at risk, you build the graph “lock A is requested before B” and look for a cycle. You program it in Deadlock risk.
Prevention 2: timeouts
lock.acquire(timeout=seconds) returns False if it cannot get the lock in time, so you can release what you hold, wait a little and retry, instead of hanging.
# Not run in the browser corrector (it cannot create real threads).
import threading
a = threading.Lock()
b = threading.Lock()
a.acquire() # someone holds A
def attempt():
if a.acquire(timeout=0.1): # waits at most 0.1 s
print("acquired")
a.release()
else:
print("could not: retry or give up")
h = threading.Thread(target=attempt)
h.start()
h.join()
# could not: retry or give up
Dependencies between tasks
A related problem: a task cannot start until others have finished. The longest chain of dependencies (the critical path) sets the minimum time, however many workers there are. You compute it in Tasks with dependencies.
Processes for heavy calculation
For CPU-bound tasks, multiprocessing (or ProcessPoolExecutor) uses several real cores, because each process has its own interpreter and its own GIL. In exchange, they do not share memory: they communicate through queues, pipes or by returning results, and starting processes costs more than starting threads.
# Not run in the browser corrector (it cannot create real threads).
from multiprocessing import Pool
def square(n):
return n * n
if __name__ == "__main__":
with Pool(4) as pool:
print(pool.map(square, range(6))) # [0, 1, 4, 9, 16, 25]
Good practices
- Choose according to the task: I/O →
asyncioor threads; CPU → processes. - Prefer passing messages (
queue.Queue,asyncio.Queue) to sharing variables. - If you share data, protect it with a
Lockand usewith; keep the critical section as short as possible. - Always request locks in the same order and avoid calling unknown code while holding one.
- Use pools (
concurrent.futures) instead of creating threads by hand. - Limit concurrency with semaphores and queues with
maxsize, so as not to saturate resources. - Measure before optimizing: concurrency adds complexity and does not always speed things up.
- Design so that the result does not depend on the order in which tasks finish, and test your logic with deterministic simulations.