Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

how can i modefy this code to make the producer thread must pause for a random p

ID: 3731215 • Letter: H

Question

how can i modefy this code to make the producer thread must pause for a random period (up to 0.2s) in its critical section.

static void* car_out_handler(void *carpark_out) {

cp_t *temp;
unsigned int seed;
temp = (cp_t *)carpark_out;
pthread_barrier_wait(&temp->bar); to ensure that all producer and cons. at the same time.
for(; ;) {

usleep(rand_r(&seed) % ONE_SECOND);

//acquire the lock
pthread_mutex_lock(&temp->lock);

while(temp->occupied == 0)
pthread_cond_wait(&temp->car, &temp->lock);

//increment counters
temp->occupied--;
temp->nextout++;
temp->nextout %= temp->capacity;
temp->cars_out++;


//somebody may be waiting on toom to become available
pthread_cond_signal(&temp->space);

//release the locl
pthread_mutex_unlock(&temp->lock);


}
return ((void *)NULL);

}

Explanation / Answer

//Code is Explained in comments:

#include <time.h> //include this header to use time functions in c_str

#include <unistd.h> //to use usleep command

static void* car_out_handler(void *carpark_out) {

cp_t *temp;

unsigned int seed;

temp = (cp_t *)carpark_out;

srand(time(NULL); //this acts a seed to absolute random number generation.

pthread_barrier_wait(&temp->bar); to ensure that all producer and cons. at the same time.

for(; ;) {

usleep(rand()%201); //since usleep can sleep upto 0.2 seconds i.e 200 milliseconds.For every random number generated,it takes reminder when divided by 201 i,e it should be of value between 0 to 200

//This is how you sleep for a random time for 0.2 secs

//acquire the lock

pthread_mutex_lock(&temp->lock);

while(temp->occupied == 0)

pthread_cond_wait(&temp->car, &temp->lock);

//increment counters

temp->occupied--;

temp->nextout++;

temp->nextout %= temp->capacity;

temp->cars_out++;

//somebody may be waiting on toom to become available

pthread_cond_signal(&temp->space);

//release the locl

pthread_mutex_unlock(&temp->lock);

}

return ((void *)NULL);

}