


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



process switch
A enters critical region
B tries to enter critical region
B enters critical region
A leaves critical region
B leaves critical region
Time
while (TRUE) { while (turn != 0) ; /* loop */ critical_region (); turn = 1; noncritical_region (); }
while (TRUE) { while (turn != 1) ; /* loop */ critical_region (); turn = 0; noncritical_region (); }
#define FALSE 0 #define TRUE 1 #define N 2 // # of processes int interested[N]; // Set to 1 if process j is interested int last_request; // Who requested entry last?
void enter_region(int process) { int other = 1 ‐process; // # of the other process interested[process] = TRUE; // show interest last_request = process; // Set it to my turn while (interested[other]==TRUE && last_request == process ) ; // Wait while the other process runs }
void leave_region (int process) { interested[process] = FALSE; // I’m no longer interested }
Code for process Pi
while (1) { while (TestAndSet(lock)) ; // critical section lock = 0; // remainder of code }
Code for process Pi
while (1) { while (Swap(lock,1) == 1) ; // critical section lock = 0; // remainder of code }
int lock = 0;
Consumer Item citm; while (1) { if (counter == 0) sleep(); citm = buffer[out]; out = (out+1) % n; counter ‐= 1; if (count == n‐1) wakeup(producer); consume the item in citm … }
Shared variables const int n; typedef … Item; Item buffer[n]; int in = 0, out = 0, counter = 0;
Atomic statements:
countercounter +=+= 1;1; countercounter ‐‐== 1;1;
Producer Item pitm; while (1) { … produce an item into pitm … if (counter == n) sleep(); buffer[in] = pitm; in = (in+1) % n; counter += 1; if (counter==1) wakeup(consumer); }
class Semaphore { int value; ProcessList pl;
void down () { value ‐= 1; if (value < 0) { // add this process to pl pl.enqueue(currentProcess); Sleep(); } }
void up () { Process P; value += 1; if (value <= 0) { // remove a process P from pl P = pl.dequeue(); Wakeup(P); } } }
Producer int in = 0; Item pitem; while (1) { // produce an item // into pitem empty.down(); mutex.down(); buffer[in] = pitem; in = (in+1) % n; mutex.up(); full.up(); }
const int n; Semaphore empty(n),full(0),mutex(1); Item buffer[n];
Consumer int out = 0; Item citem; while (1) { full.down(); mutex.down(); citem = buffer[out]; out = (out+1) % n; mutex.up(); empty.up(); // consume item from // citem }