The following class implements a queue based on bounded-buffer in which the embedded items array is a circular buffer with two index variables head and tail (a circular buffer is “full” when there is one empty slot left in the array). The member variable mx is a mutex variable, and empty and full are two condition variables. Assume any mutex variable m has two methods m.lock() and m.unlock(), and any condition variable c has two methods: c.wait(&m) and c.signal().
After an item is produced, a producer invokes add() which deposits the item to the array location indexed by tail. Before consuming an item, a consumer invokes remove() which reads and removes the item from the array location indexed by head. The constructor has been implemented and the circular buffer is initialized to be empty. Implement the add() and remove() methods in C (no need to have actual .c program). Note an array in C is 0-based. You cannot modify existing code and cannot have any additional synchronization constructs.
class bounded_queue {
int items[MAX_ITEMS]; /* circular buffer, the constant MAX_ITEMS is defined elsewhere */
int head;
int tail;
mutex mx;
condition full, empty; /* condition variable */
bounded_queue() {head = tail = 0;}; /* constructor, empty buffer */
void add(int v); /* deposit the value v to the tail of the items array */
int remove(); /* remove an item from the head of the items array, and return the value */
}
Answers
Answered by
2
Answer:
So much long question
Similar questions