Question: They are asking me to complete the producer/consumer program using C. they gave me the code below, but im not sure exactly what im missing.

They are asking me to complete the producer/consumer program using C. they gave me the code below, but im not sure exactly what im missing.

#include

#include

#include //compile and link with -pthread

#define BUFFER_SIZE 10

int buffer[BUFFER_SIZE];

int in, out;

int num;

void *produce( void *ptr ) {

int item;

while(1){

usleep(rand() % 1000); //sleep

printf("Producer wants to produce. ");

//critical section below

item = rand() % 10;

num++;

buffer[in] = item;

in = (in + 1) % BUFFER_SIZE;

//critical section above

printf("Producer entered %d. Buffer Size = %d ", item, num);

}

}

void *consume( void *ptr ) {

int item;

while(1){

usleep(rand() % 1000); //sleep

printf("Consumer wants to consume. ");

//critical section below

num--;

int item = buffer[out];

out = (out + 1) % BUFFER_SIZE;

//critical section above

printf("Consumer consumed %d. Buffer Size = %d ", item, num);

}

}

int main() {

pthread_t consumer, producer;

out = 0; //index of the item to be consumed next

in = 0; //index of the item to be produced next

num = 0; //number of items in the buffer

srand(time(NULL));

pthread_create( &consumer, NULL, consume, NULL);

pthread_create( &producer, NULL, produce, NULL);

pthread_join( producer, NULL);

pthread_join( consumer, NULL);

pthread_exit(NULL);

}

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 Databases Questions!