Given the following producer&consumer problem solution, what is the potential ri
ID: 3715235 • Letter: G
Question
Given the following producer&consumer problem solution, what is the potential risk in the code when the solution is running on a single CPU, multitasking operating system? Assume we need run multiple producers and consumers at the same time, modify the code to remove the risk using any solution that is proper.
Producer:
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Consumer:
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}
Explanation / Answer
Producer Consumer Problem - In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.
The Producer - The producer's job is to generate data, put it into the buffer, and start again.
The Consumer - At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time.
Potential Risk - The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
Solution to the Problem - The solution for the producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be reached by means of inter-process communication, typically using semaphores. An inadequate solution could result in a deadlock where both processes are waiting to be awakened
The Code for Producer and Consumer after removing risk is:-
int mutex=1,full=0,empty=3,x=0;
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
Producer:
while (true) {
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
mutex=signal(mutex);
}
Consumer:
while (true) {
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
mutex=signal(mutex);
/* consume the item in nextConsumed */
}
Please let me know in case of any clarifications required. Thanks!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.