Bounded buffer problem solution

Document Sample
 Bounded buffer problem solution Powered By Docstoc
					// Bounded buffer problem solution using semaphores – pclab5.cm
#include "bddbuff.inc" const int ValueRange = 20; // 0-19 will be produced and consumed semaphore to; // exclusive access to output semaphore s; // mutual exclusion for buffer semaphore n; // # consumable items in buffer semaphore e; // # empty spaces in buffer int produce(char id) { int tmp; tmp = random(ValueRange); wait(to); cout << "Producer " << id << " produces " << tmp << endl; signal(to); return tmp; } void consume(char id, int i) { wait(to); cout << "Consumer " << id << " consumes " << i << endl; signal(to); } void producer(char id) { int i; for (;;) { //loop forever - can't use for loop here! i = produce(id); // FILL IN TWO SEMAPHORE OPERATIONS: append(i); //FILL IN TWO MORE SEMAPHORE OPERATIONS: } void consumer(char id) int i; for (;;) { } { //loop forever - can't use for loop here!

//bddbuff.inc
const int SizeOfBuffer = 5; int buffer[SizeOfBuffer]; int in = 0; //index to use for next append int out = 0; //index to use for next take void append(int v) //add v to buffer { buffer[in] = v; in = (in + 1) % SizeOfBuffer; } int take() //return an item from the buffer { int tmp; tmp = buffer[out]; out = (out + 1) % SizeOfBuffer; return tmp; }

// FILL IN TWO SEMAPHORE OPERATIONS: i = take(); //FILL IN TWO MORE SEMAPHORE OPERATIONS: consume(id,i); } } main() { // INITIALIZE EACH SEMAPHORE PROPERLY initialsem(s,?); initialsem(n,?); initialsem(e,?); initialsem(to,?); cobegin { producer('A'); producer('B'); consumer('x'); consumer('y'); consumer('z'); } }


				
DOCUMENT INFO