Question: multiple producers and consumers c++ problem: the program will need thread for each producer and consumer. As each thread produces or consumes a data item,

multiple producers and consumers c++ problem:

the program will need thread for each producer and consumer. As each thread produces or consumes a data item, it will print its status.

please use sem_t empty; sem_t full; pthread_mutex_t mutex;

program:

void * producer(void * arg) {

int myNum = producer_num.fetch_add(1) + 1;

while(true) {

sleep(rand() % 5 + 1);

int item = rand() % 100 + 1;

// TODO: Implement the meat of the producer algorithm, using any semaphores and

// mutex locks that are needed to ensure safe concurrent access.

// After producing your item and storing it in the buffer, print a line

} }

void * consumer(void * arg) {

int myNum = consumer_num.fetch_add(1) + 1;

while(true) { TODO: Implement the meat of the consumer algorithm, using any semaphores and

// mutex locks that are needed to ensure safe concurrent access.

//

// After consuming your item and storing it in "item", print a line in the following format: : slept , produced in slot

} }

int main(int argc, char ** argv)

{

// Usage: bounded_buffer

// TODO: Allocate your buffer as an array of the correct size based on the command line argument

// TODO: Initialize the semaphore(s) you are using in your algorithm.Use the function sem_init()

srand(time(NULL));

pthread_attr_t attr;

pthread_attr_init(&attr);

for (int i = 0; i < num_producers; ++i) {

pthread_t thread_id;

pthread_create(&thread_id, &attr, producer, NULL); }

for (int i = 0; i < num_consumers; ++i) {

pthread_t thread_id;

pthread_create(&thread_id, &attr, consumer, NULL); }

sleep(run_time);

exit(0);

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!