Concurrency & Synchronization
The problem
When multiple threads read and write the same memory at the same time, the outcome depends on the precise, unpredictable interleaving of their instructions — without a way to coordinate access, the same program can silently produce different results on different runs.
Why now
Processes and threads established that threads share memory; mutability-and-references already showed that shared, mutable data is where aliasing bugs live — synchronization is that same problem, now happening simultaneously across multiple independent lines of execution instead of sequentially in one.
Mental model
A race condition happens when the correctness of a result depends on timing that isn't guaranteed. A lock (mutex) fixes this by making a section of code exclusive — only one thread can be inside at a time, everyone else waits — trading a bit of parallelism for a guarantee that shared state is never read or written mid-update by two threads at once.
Requires
- Processes & ThreadsOperating Systems
Synchronization problems only exist because threads share memory; you need the shared-memory model from processes-and-threads before race conditions have anywhere to occur.
- Mutability & ReferencesProgramming Fundamentals
A race condition is exactly the aliasing problem from mutability-and-references, but with two threads racing to read-modify-write the same reference instead of two sequential lines of code doing it.
Unlocks
Related
Used in
- Mutexes, semaphores, and locks in every concurrent programming language
- Database transaction isolation (preventing concurrent writes from corrupting data)
- Thread-safe data structures in concurrent systems
- Debugging flaky, hard-to-reproduce bugs that only appear under load
Projects
- Reproduce a race condition with two threads incrementing a shared counter without a lock, then fix it with a mutex and verify the result is now always correct
- Explain, step by step, an interleaving of two threads that produces an incorrect result on an unsynchronized shared counter
Examples
- Two threads both reading counter=5, both computing 6, both writing 6 — one increment is silently lost
- A mutex around a bank account balance update ensures a withdrawal and a deposit can never interleave mid-update
Resources
- Concurrency — MIT 6.033course
Mastery checklist
- I can explain what a race condition is and construct a minimal example
- I can explain how a mutex/lock prevents a race condition
- I can identify shared mutable state in a piece of concurrent code as a synchronization risk
- I can explain the performance cost a lock introduces and why it's still worth it for correctness