Chapter 9: Threads and Synchronization — Doppelgangers and Collaboration
Vol 3: Computer Core Expedition · Chapter 9
Metadata Card
| Attribute | Value |
|---|---|
| Keywords | Thread Models, Mutex, Semaphore, Condition Variable, Deadlock |
Your Progress
"You now know that a process is an isolated world. But what if you want multiple execution streams within the same world, sharing the same memory? That's where threads come in."
Encounter 1: Threads vs Processes
| Process | Thread | |
|---|---|---|
| Address space | Separate | Shared |
| Context switch cost | High (TLB flush) | Low |
| Communication | IPC (pipes, sockets) | Shared memory |
| Isolation | Strong | Weak |
Encounter 2: Race Conditions
When multiple threads access shared data without synchronization, the result depends on the unpredictable timing of thread interleaving.
c
// Race condition: two threads both increment counter
counter++; // read, add, write — three operations that can interleaveEncounter 3: Mutex (Mutual Exclusion)
c
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void thread_safe_increment() {
pthread_mutex_lock(&mutex);
counter++; // Protected section
pthread_mutex_unlock(&mutex);
}Encounter 4: Semaphore
A counter used to control access to a pool of resources:
sem_wait(sem): Decrement, block if zerosem_post(sem): Increment, wake a waiting thread
Encounter 5: Deadlock
Four necessary conditions:
- Mutual exclusion: Resource cannot be shared
- Hold and wait: Thread holds one resource while waiting for another
- No preemption: Resource can't be forcibly taken
- Circular wait: Threads form a circular dependency chain
Verification Checklist
- [ ] Can explain the difference between processes and threads
- [ ] Can identify and fix a race condition with a mutex
- [ ] Can explain the difference between mutex and semaphore
- [ ] Can identify the four deadlock conditions
→ Next Stop Preview
Chapter 10: CPU Scheduling