Lecture 8 - Process Synchronization, Semaphores
boolean TestAndSet(boolean *target) { boolean orig_val = *target; *target = TRUE; return orig_val; }
boolean lock = false;
while (1) { while (TestAndSet(&lock)); /* busy wait */ /* critical section */ lock = false; /* non-critical section */ }
boolean lock=false; boolean waiting[n]; /* all initialized to false */
int j; boolean key; while (1) { waiting[i]=true; key=true; while (waiting[i] && key) key = TestAndSet(&lock); waiting[i]=false; /* critical section */ j=(i+1)%n; while ((j!=i) && !waiting[j]) j=(j+1)%n; if (j==i) lock=false; else waiting[j]=false; /* non-critical section */ }
semaphore mutex=1;
while (1) { wait(mutex); /* critical section */ signal(mutex); /* non-critical section */ }
semaphore fullslots, emptyslots, mutex; full=0; empty=n; mutex=1;
while (1) { produce item; wait(emptyslots); wait(mutex); add item to buffer; signal(mutex); signal(fullslots); }
while (1) { wait(fullslots); wait(mutex); remove item from buffer; signal(mutex); signal(emptyslots); consume item; }
mutex provides mutual exclusion for the modification of the buffer (not shown in detail). The others make sure that the consumer doesn't try to remove from an empty buffer (fullslots is > 0) or that the producer doesn't try to add to a full buffer (emptyslots is > 0).
See examples on the next lecture's page.