Question: Producer and Consumer Code in C++ The program will contain two methods- one each for the producer and consumer. Both methods share access to an
Producer and Consumer Code in C++
The program will contain two methods- one each for the producer and consumer. Both methods share access to an integer array buffer of size 50 with all values initialized to 0 at the beginning and an integer variable counter initialized to 0. As given below, the producer accesses the buffer elements and updates the element to 1 ( indicating production). The consumer changes a buffer elements to 0 (indicating consumption).
Enhancements and modifications:
- You will modify both the methods to generate a random number between 1-5.
-The random number for the producer indicates to the producer how many elements to produce.
-The number for the consumer indicates the number of elements to be consumed by the consumer.
- Each method will output the value of the counter upon entering and before exiting.
- If the producers random number is larger than the empty buffer positions, the producer will produce only the amount that fits on the buffer and output an appropriate message. Similarly, if the consumer does not have enough elements in the buffer to consume, the consumer will consume the number in the buffer and output an appropriate message.
- The methods will be called in a loop that will be repeated x times. You can choose a value of x- sufficient to show the processes are working.
Within the loop, the methods will be called randomly based on a random number. For example, if the number generated is 0 then the producer method is called and if the number generated is 1, the consumer is called.
Pseudo Code:
//PRODUCER- producing one element
{ /* produce an item in next produced */
while (counter == BUFFER_SIZE) ;
/* do nothing */
buffer[in] =1; // next_produced
in = (in + 1) % BUFFER_SIZE;
counter++;
}
//CONSUMERconsuming one element
{
while (counter == 0)
; /* do nothing */
buffer[out]= 0;// next_consumed
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
