4/24/2016 1
Operating Systems Principles Higher Level Synchronization
Mark Kampe (markk@cs.ucla.edu)
Higher Level Synchronization
9A. Practical Problems – locking and waiting 9B. Semaphores and Condition Variables 9C. File Level Locking 9D. Bottlenecks, Contention and Granularity
Higher Level Synchronization 2
Using Condition Variables
pthread_mutex_t lock = PTHEAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHEAD_COND_INITIALIZER; … pthread_mutex_lock(&lock); while (ready == 0) pthread_cond_wait(&cond, &lock); pthread_mutex_lock(&lock) … if (pthread_mutex_lock(&lock)) { ready = 1; pthread_mutex_signal(&cond); pthread_mutex_unlock(&lock); }
IPC, Threads, Races, Critical Sections 3
The Bounded Buffer Problem
void producer( FIFO *fifo, char *msg, int len ) { for( int i = 0; i < len; i++ ) { pthread_mutex_lock(&mutex); while (fifo->count == MAX) pthread_cond_wait(&empty, &mutex); put(fifo, msg[i]); pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); } }
Higher Level Synchronization 4
void consumer( FIFO *fifo, char *msg, int len ) { for( int i = 0; i < len; i++ ) { pthread_mutex_lock(&mutex); while (fifo->count == 0) pthread_cond_wait(&fill, &mutex); msg[i] = get(fifo); pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); } }
Semaphores – signaling devices
when direct communication was not an option
e.g. between villages, ships, trains
Semaphores - History
- Concept introduced in 1968 by Edsger Dijkstra
– cooperating sequential processes
- THE classic synchronization mechanism
– behavior is well specified and universally accepted – a foundation for most synchronization studies – a standard reference for all other mechanisms
- more powerful than simple locks
– they incorporate a FIFO waiting queue – they have a counter rather than a binary flag
Higher Level Synchronization 6