Skip to content

Chapter 9: Threads and Synchronization — Doppelgangers and Collaboration

Vol 3: Computer Core Expedition · Chapter 9


Metadata Card

AttributeValue
KeywordsThread 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

ProcessThread
Address spaceSeparateShared
Context switch costHigh (TLB flush)Low
CommunicationIPC (pipes, sockets)Shared memory
IsolationStrongWeak

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 interleave

Encounter 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 zero
  • sem_post(sem): Increment, wake a waiting thread

Encounter 5: Deadlock

Four necessary conditions:

  1. Mutual exclusion: Resource cannot be shared
  2. Hold and wait: Thread holds one resource while waiting for another
  3. No preemption: Resource can't be forcibly taken
  4. 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

Built with VitePress | Software Systems Atlas