150k views
5 votes
The producer thread will alternate between sleeping for a random period of time and inserting a random integer into the buffer. Random numbers will be produced using the rand_r(unsigned int *seed) function, which produces random integers between 0 and RAND_MAX safely in multithreaded processes. The consumer will also sleep for a random period of time and, upon awakening, will attempt to remove an item from the buffer. An outline of the producer and consumer threads appears as:

1 Answer

4 votes

Answer:

// Producer Thread

void *producer(void *param) {

buffer_item item;

while (true) {

item = rand() % 100;

sem_wait(&empty);

pthread_mutex_lock(&mutex);

if (insert_item(item))

printf("Can't insert item\\");

else

printf("Producer %d: produced %d\\", *((int*)param), item);

pthread_mutex_unlock(&mutex);

sem_post(&full);

}

}

// Consumer Thread

void *consumer(void *param) {

while (true) {

buffer_item item = NULL;

if (in > 0)

item = buffer[in - 1];

sem_wait(&full);

pthread_mutex_lock(&mutex);

if (remove_item(&item))

printf("Can't remove item\\");

else

printf("Consumer %d: consumed %d\\", *((int*)param), item);

pthread_mutex_unlock(&mutex);

sem_post(&empty);

}

}

Step-by-step explanation:

An outline of the producer and consumer threads appears as shown above.

User JaChNo
by
4.8k points