3. The following implementation is an attempt to solve the problem for one produ
ID: 3831253 • Letter: 3
Question
3. The following implementation is an attempt to solve the problem for one producer and multiple consumers as shown in Problem 2.
Problem 2:
Producer Thread:
void *producer(void *arg) {
for (int i=0; i<loops; i++) { //p1
Mutex_lock(&m); //p2
while(numfull == max) //p3
Cond_wait(&cond, &m); //p4
do_fill(i);//p5
Cond_signal(&cond); //p6
Mutex_unlock(&m); //p7
}
}
Consumer Thread:
void *consumer(void *arg) {
while(1) { //c1
Mutex_lock(&m); //c2
while(numfull == 0) //c3
Cond_wait(&cond, &m); //c4
int tmp = do_get(); //c5
Cond_signal(&cond); //c6
Mutex_unlock(&m); //c7
}
}
Problem 3.
void *producer(void *arg) {
for (int i = 0; i < loops; i++) { //p1
Mutex_lock(&m); // p2
if (numfull == max) // p3
Cond_wait(&empty, &m); // p4
do_fill(i); // p5
Cond_signal(&fill); // p6
Mutex_unlock(&m); //p7
}
}
void *consumer(void *arg) {
while (1) { //c1
Mutex_lock(&m); //c2
if (numfull == 0) //c3
Cond_wait(&fill, &m); //c4
int tmp = do_get(); //c5
Cond_signal(&empty); //c6
Mutex_unlock(&m); //c7 }
}
A. Would it work?
B. If it works, show a schedule to make it work. Otherwise, describe a different schedule to show the problem. Fill out the following table for the schedule. (You don’t have to fill out all blanks if they are not applicable):
C. If it does not work, how to fix it? (Ignore this question if it works)
Actions Producer State Consumer 1 State Consumer 2 State Numfill valueExplanation / Answer
Considering that you have a knowledge about the mutex, semaphores and multi-threading, i would jump to the solution of the question.
Looking into the code, we can see that the producer does nothing as long as the 'numfull' is full. For any other other state of 'numfull', producer will be executing the 'do_fill' function with the value of i and continue to do so till i reaches the value 'loops'.
Similarly, the consumer does nothing as long as the 'numfull' state is empty. For any other state of 'numfull' consumer will be executing the 'do_get' function with the value of i and continue to do so till i reaches the value of 0.
Actions Producer State Consumer 1 State Consumer 2 State Numfill value 1 do_fill(0) does nothing does nothing 0 2 do_fill(1) do_get(1) do_get(1) 1 3 do_fill(3) do_get(2) do_get(2) 2 . . . . . . . . . . loop do_fill(loop) do_get(loop) do_get(loop) loopRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.