The following partial code is a bounded-buffer monitor in which the buffers are
ID: 3677620 • Letter: T
Question
The following partial code is a bounded-buffer monitor in which the buffers are embedded within the monitor (with two condition variables). Assume any codition variable cond has two methods: cond.wait() and cond.signal(). Please implement the produce() and consume() methods. You cannot modify existing code and cannot have any additional synchronization mechanisms.
monitor bounded_buffer {
int items[MAX_ITEMS]; /*MAX_ITEM is a constant defined elsewhere*/
int numItems = 0; /*# of items in the items array*/
condition full, empty;
void produce(int v); /*deposit the value v to the items array*/
int consume(); /*remove the last item from items, and return the value*/
}
Explanation / Answer
monitor bounded_buffer {
int head, tail;
int items[MAX_ITEMS]; /*MAX_ITEM is a constant defined elsewhere*/
int numItems = 0; /*# of items in the items array*/
condition full, empty;
void produce(int v); /*deposit the value v to the items array*/
int consume(); /*remove the last item from items, and return the value*/
}
void produce(int v)
{
while(tail == head+ MAX_ITEMS)
wait (empty);
items[tail++ % MAX_ITEMS] = v;
signal(full);
}
int consume()
{
while (head == tail)
wait (full);
int v1= items[head++ % MAX_ITEMS];
signal(empty);
return v1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.