Preemptive Context Switching: A process can’t anticipate context yields
Synchronization: Control the multi-threaded behavior when execution order is random
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
Hardware-provided Atomic Instruction
test_and_set
Record old value and set new value of a variableLock States: Locked - held, unlocked - free.
lock()
Blocking call that returns when the thread acquired the lockunlock()
Release the lockSpin Lock: while (test_and_set(*lock, 1) == 1);
Sleep Lock: Use a spin-locked queue of waiting threads
Condition Variable Procedure:
Condition Variable Operations:
pthread_cond_wait(cv, mutex)
Release mutex, enqueue, sleep, re-acquire mutexpthread_cond_signal(cv)
Wake one queued threadpthread_cond_broadcast(cv)
Wake all queued threadsLost 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