Question: #include #include #include const int N = 2 ; / / Number of threads ( producer and consumer ) std::vector flag ( N , false
#include
#include
#include
const int N ; Number of threads producer and consumer
std::vector flagN false; Flags to indicate readiness
int turn ; Variable to indicate turn
void producerint j
do
flagj true; Producer j is ready to produce
turn j; Allow consumer to consume
while flag j && turn j
Wait for consumer to finish
Producer waits if consumer is ready and it's consumer's turn
Critical Section: Producer produces an item and puts it into the buffer
flagj false; Producer is out of the critical section
Remainder Section: Additional actions after critical section
while true; Continue indefinitely
void consumerint i
do
flagi true; Consumer i is ready to consume
turn i; Allow producer to produce
while flag i && turn i
Wait for producer to finish
Consumer waits if producer is ready and it's producer's turn
Critical Section: Consumer consumes an item from the buffer
flagi false; Consumer is out of the critical section
Remainder Section: Additional actions after critical section
while true; Continue indefinitely
int main
std::thread producerThreadproducer; Create producer thread
std::thread consumerThreadconsumer; Create consumer thread
producerThread.join; Wait for producer thread to finish
consumerThread.join; Wait for consumer thread to finish
return ;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
