Unit content
Concurrency, interleavings and race conditions
Concurrency means that several tasks can make progress during the same period. Their operations can interleave in different orders even when only one processor executes them at a time.
Parallelism is stronger: work actually executes simultaneously on different processing resources.
Interleavings
Suppose two tasks both execute a read-modify-write increment:
read counter
add 1
write counter
The individual operations from the two tasks can interleave. Both can read the same old value before either writes, so one update is lost.
Race conditions
A race condition exists when correctness depends on which valid timing or ordering happens to occur.
Races are difficult because testing one execution does not explore every possible interleaving. Adding logging or changing timing can even make the failure disappear.
Shared mutable state
Independent or immutable state avoids many races. When tasks must coordinate shared mutation, the program needs an explicit synchronization contract.
Concurrency is therefore first a reasoning problem: identify which operations can overlap and which invariants must hold under every permitted interleaving.