100 likes | 201 Views
SCRIBE OF DATE:26-02-2014. Sathu Hareesh Babu 11CS10039. Producer Consumer Problem-Tasks. We must ensure proper synchronization - Stop the consumer when buffer is empty. - Stop the producer when buffer is full. We must ensure mutual exclusion
E N D
SCRIBE OF DATE:26-02-2014 Sathu Hareesh Babu 11CS10039
Producer Consumer Problem-Tasks • We must ensure proper synchronization - Stop the consumer when buffer is empty. - Stop the producer when buffer is full. • We must ensure mutual exclusion - That is,we should avoid race condition. • Piggybank the wakeup signals • Avoid busy waiting.
Semaphore • Semaphore is a widely used synchronization tool. • Busy waiting is not required - CPU is not held unnecessarily while the process is waiting. • A semaphore S is a data structure with • An integer variable S.value • A queue S.list of processes(shared variable) • The data structure can only be accessed by two atomic operations wait(S) and signal(S)(also called down(S),P(S) and Up(S),V(S).
Semaphore • Value of Semaphore S = Value of the integer S.value. • Semaphore data structure typedefstruct{ int value; struct process *list; }semaphore
Semaphore Wait(S) • Wait(S) S<= Semaphore variable • When a process P executes the wait(S) and finds • S == 0 • Process must wait => block() • Switch from running to waiting state • Places the process into a waiting queue associated with S
Semaphore • Wait(S) • P executes wait(S) if(s > 0) s-- ; else if s == 0 P waits(placed in waiting queue)
Semaphore Signal(S) • Signal(S) When a process P executes the signal S. • Check, if some other process Q is waiting on the semaphore S • Wakeup(Q) • Wakeup(Q) changes the process from waiting to ready state
Semaphore • Signal(S) if(s>0) s++; else if s==0 if no process waiting -> s++ else wake one of the processes up.
Semaphore(wait and signal) • Implementation of wait; wait(semaphore *S) { S->value--; if (S->value < 0) { add this process to S->list; block(); } } PCB List
Semaphore(wait and signal) • Implementation of signal: signal(semaphore *S) { S->value++; if (S->value <= 0) { remove a process P from S->list; wakeup(P); } }