Module Review: Concurrency
Key Takeaways
- Concurrency is Hard: Without synchronization, Race Conditions corrupt shared state because operations like
count++are not atomic. - Hardware Matters: Synchronization primitives (Mutexes, Semaphores) rely on hardware atomic instructions like Test-and-Set and Compare-and-Swap.
- Locks vs Signals: Use Mutexes for mutual exclusion (protecting data). Use Semaphores or Condition Variables for coordination (signaling between threads).
- Deadlocks: Occur when the 4 Coffman Conditions are met. Prevent them by imposing a global Resource Ordering.
-
Modern Approaches: Higher-level abstractions like Monitors (Java) and Channels (Go/CSP) reduce the risk of errors compared to raw Semaphores.
Module Review: Concurrency
[!NOTE] This module explores the core principles of Module Review: Concurrency, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.
1. Interactive Flashcards
What is a Race Condition?
A situation where the program's output depends on the uncontrollable timing of thread scheduling (context switches).
What is the Critical Section?
The part of the code that accesses shared resources and must be executed by only one thread at a time.
What is Busy Waiting?
When a thread repeatedly checks a condition in a loop (Spinlock), wasting CPU cycles instead of sleeping.
Difference between Mutex and Binary Semaphore?
A Mutex has Ownership (only the locker can unlock). A Semaphore is a signal (anyone can V/Signal).
What are the 4 Coffman Conditions for Deadlock?
1. Mutual Exclusion
2. Hold and Wait
3. No Preemption
4. Circular Wait
2. Hold and Wait
3. No Preemption
4. Circular Wait
What is the "MESA Semantics" rule?
Always use a while loop to check the condition after waking up from a
wait(), because the state might have changed again.2. Cheat Sheet: Synchronization Primitives
| Primitive | Mechanism | Pros | Cons | Use Case |
|---|---|---|---|---|
| Spinlock | Busy Wait Loop | Very Fast (No Context Switch) | Wastes CPU | Kernel / Drivers |
| Mutex | Sleep Queue | Efficient CPU Usage | High Latency (Context Switch) | General App Logic |
| Semaphore | Counter + Sleep | Coordination / Signaling | Easy to deadlock / leak | Producer-Consumer |
| Monitor | Mutex + CV | Encapsulated / Safer | MESA Semantics tricky | Java Objects |
| Channel | Message Passing | Decoupled / Thread-Safe | Can be slower than locks | Go / Rust |
3. Next Steps
Now that you understand how to ensure threads don’t crash into each other, let’s explore how the OS stores data persistently.