Preemptive Context Switching: A process can’t anticipate context yields

Synchronization: Control the multi-threaded behavior when execution order is random

  1. Critical Section: Enforce only one use of a shared resource at any time
  2. Ordering: Control order of thread execution

Critical Section

Critical Section Requirements

Mutual Exclusion: Only one thread can execute in the critical section at a time

Fairness: When the critical section is free, all threads have fair chance to enter

Performance: Overhead of lock & unlock CS is small wrt the actual task

Atomic Instructions

Hardware-provided Atomic Instruction

Locks

Lock States: Locked - held, unlocked - free.

Spin Lock: while (test_and_set(*lock, 1) == 1);

Sleep Lock: Use a spin-locked queue of waiting threads

Condition Variables

Condition Variable Procedure:

  1. Hold a lock while checking the shared condition
  2. If the condition doesn’t satisfy, release lock and sleep
  3. Re-acquire lock when waking up, do stuff.

Condition Variable Operations:

Lost Wakeup Problem: Wait thread stuck on wait when signal happens before wait

pthread_mutex_lock(mutex);
while(!condition) 
	pthread_cond_wait(cond, mutex);

// Do stuff

pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);

Application Example