Concurrency and Synchronization
Understand race conditions and critical sections, and solve them with mutexes, semaphores, condition variables and atomics, including the classic synchronization problems.
Intermediate · about 8 hours · difficulty 4/5
Learn first: Processes and Threads
When threads share data, the order of their operations becomes unpredictable. Synchronization is how you make shared state correct again, and it is one of the most asked (and most misunderstood) OS topics.
The problem
- A race condition happens when the result depends on timing.
count++is really read, add, write; two threads can both read 5 and both write 6. - The code that touches shared state is the critical section. A correct solution needs mutual exclusion, progress and bounded waiting.
Tools
- Mutex (lock): only the owner can unlock. Use it to guard a critical section. Keep critical sections short.
- Semaphore: an integer counter with
wait(P) andsignal(V). A binary semaphore acts like a lock; a counting semaphore limits access to N resources, such as a pool of 5 database connections. - Condition variable: wait until a condition becomes true, always inside a loop that re-checks the condition (spurious wakeups).
- Atomics and compare-and-swap for lock-free counters.
- Spinlock: busy waits; good only for very short waits on multicore machines.
- Peterson's solution is a classic software-only algorithm worth knowing for theory questions.
Classic problems
- Producer-consumer (bounded buffer): two counting semaphores (empty, full) plus a mutex.
- Readers-writers: many readers or one writer; watch for writer starvation.
- Dining philosophers: illustrates deadlock; fix by ordering resources or limiting diners.
Pitfalls
Forgetting to unlock on an error path (use RAII lock_guard in C++ or try/finally in Java), locking in inconsistent order across threads, and using if instead of while around a condition wait.
Good enough to move on: you can write a correct bounded-buffer producer-consumer and explain mutex vs semaphore without mixing them up.
Key concepts
- Race conditions and critical sections
- Mutex and locks
- Binary and counting semaphores
- Condition variables
- Producer-consumer problem
- Readers-writers problem
- Dining philosophers
- Atomics and spinlocks
- Peterson's solution
Mini project
Implement a thread-safe bounded blocking queue using a mutex and two condition variables, stress test it with 4 producers and 4 consumers, and show that removing the lock produces lost or duplicated items.
Check yourself
What is the difference between a mutex and a binary semaphore, and why must a condition variable wait be wrapped in a while loop?
Free resources
- OSTEP: Concurrency chapters (OSTEP)
- The Little Book of Semaphores (Green Tea Press)
- LeetCode Concurrency problems (LeetCode)