Assume there are n slots capable of holding one item. Process producer will produce items to fill slots and process consumer will consume the items in these slots. There is no information on the relative speeds of processes. Devise a protocol which will allow these processes to run concurrently.

A common buffer whose elements (slots) will be filled/emptied by the producer/consumer is needed. The consumer should not try to consume items which have not been produced yet (i.e. the consumer can not consume empty slots). The producer should not try to put item into filled slots.

# define N 100 /* number of slots in the buffer */
typedef int semaphore; /* semaphores are a special kind of int */
semaphore mutex = 1; /* controls access to CS */
semaphore empty = N; /* counts empty buffer slots */
semaphore full = 0; /* counts full buffer slots */
void producer(void)
{
 int item;
while (TRUE) /* infinite loop */
{
 produce_item(item) /* generate something to put into buffer */
 down(empty); /* decrement empty count */
 down(mutex); /* enter CS */
 enter_item(item); /* put new item in buffer */
 up(mutex); /* leave CS */
 up(full); /* increment count of full slots */
}
}
void consumer(void)
{
 int item;
 while (TRUE) /* infinite loop */
 {
 down(full); /* decrement full count */
 down(mutex); /* enter CS */
 remove_item(item); /* take item from buffer */
 up(mutex); /* leave CS */
 up(empty); /* increment count of empty slots */
 consume_item(item); /* do something with the item */
 }
}
Share with : Share on Linkedin Share on Twitter Share on WhatsApp Share on Facebook