Question: 6 (20 points).Below is the solution for the producer consumer problem that was discussed in class. The solution assumes a single producer only and a

6 (20 points).Below is the solution for the producer consumer problem that was discussed in class. The solution assumes a single producer only and a single consumer only.

(1) Generalize the solution to deal with a fixed number N of producers and a fixed number M of consumers. Your solution must use semaphores. Do not use a monitor.

(2) Give an informal justification for the correctness of your solution.

#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 critical region */

semaphore empty = N; /* counts empty buffer slots */

semaphore full = 0; /* counts full buffer slots */

// initially: empty+full = N + 0 = N

void producer(void) {

int item;

while (TRUE) { /* TRUE is the constant 1 */

item = produce_item( );/* generate something to put in buffer */

down(&empty); /* check that buffer has >= 1 empty slot */

down(&mutex); /* enter critical region */

insert_item(item); /* put new item in buffer */

up(&mutex); /* leave critical region*/

up(&full); /* signal to consumer that buffer contains >= 1 one item */

}

}

void consumer(void) {

int item;

while (TRUE) { /* infinite loop */

down(&full); /* check that buffer contains >= 1 one item */

down(&mutex); /* enter critical region */

item = remove_item() /* take item from buffer */

up(&mutex); /* leave critical region*/

up(&empty); /* signal to producer that buffer has >=1 empty slot */

consume_item(item) /* do something with the item */

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!