250 likes | 779 Views
SEMAPHORES. Scribe: Operating systems(27/02/2014) By Salman Ahmad (11cs10041). WAIT(S). When a process executes wait(s) and finds that s==0, then Process must wait =>block() Places the process into a waiting queue associated with s Switch from running state to waiting state. SIGNAL(S).
E N D
SEMAPHORES Scribe: Operating systems(27/02/2014) By Salman Ahmad (11cs10041)
WAIT(S) When a process executes wait(s) and finds that s==0, then Process must wait =>block() Places the process into a waiting queue associated with s Switch from running state to waiting state.
SIGNAL(S) When a process P executes the signal(s),then Check if some other process Q is waiting on semaphore S and then wakeup(Q) Q changes from waiting state to ready state
Types of Semaphores Counting Semaphore Binary Semaphore Integer value can range over Integer value can range only unrestricted domain between 0 and 1 =>for synchronization => for mutual exclusion and purposes also known as mutex locks
Example problem I f we have two processes Pi and Pj .Let us say process Pi have statement A and process Pj have statement B and problem is that How to ensure that A in Pi always executes before B in Pj??
Example problem (cont...d) Solution: Keep a binary semaphore S, signal(s) after statement A and wait(s) before B in this way we can ensure that A always executes before B Note: At start semaphore S is initialized with value s==0.
To ensure mutual exclusion Say we have semaphore mutex=1(shared variable) Entry section: wait(mutex) Critical section code Exit section: signal(mutex)
Semaphores for producer-consumer problem 2 counting semaphores: full , Empty Full counts slots that are full , initially =0 Empty counts that are empty , initially=N 1 binary semaphore mutex Initially full=0, empty=N, mutex=1
Producer-consumer problem (cont...d) In consumer , down(&full) i.e. if full==0 (buffer is empty) then consumer blocks on semaphore full. In producer , down(&empty) i.e. if empty==0 (buffer is full) then producer blocks on semaphore empty Down(&mutex) and up(mutex) ensure the mutual exclusion.
Structure of producer process using semaphores do { // produce an item in nextp wait(empty); wait(mutex); // add nextp to buffer signal(mutex); signal(full); }while (TRUE) ;
Structure of consumer process using semaphores do { wait(full); wait(mutex); // remove an item from buffer to nextc signal(mutex); signal(empty); // consume the item in nextc }while (TRUE);