Suppose we have two threads, in a producer/consumer arrangement that are communi
ID: 3852327 • Letter: S
Question
Suppose we have two threads, in a producer/consumer arrangement that are communicating via a first-in-first-out buffer. The producer thread deposits data into the buffer, and the consumer thread removes data from the buffer. The following variables define a simple circular buffer that can store double values: #define BUFFERS IZE 50 double buffer [BUFFERSIZE];//The data buffer int inIndex = 0;//Next item goes in at this index int outIndex = 0;//Next item comes out from this index int count= 0;//Number of items inthe buffer Here is the essence of the code for the bufferPut function: void bufferPut (double data) { if(count==BUFFERS!ZE){//buffer is full, wait} buffer [inIndex] = data: inIndex++: if(inIndx==BUFFERSIZE){ inIndex= 0: } count++: } When the buffer becomes full, the producer will need to wait. Similarly when the buffer becomes empty, the consumer will need to wait. The pthread library provides condition variables to help solve this problem. (a) Explain how to create and initialise a pthread condition variable (You may assume default attributes will be used.) (b) What additional variables will be needed for the buffer to allow it to operate correctly in this producer/consumer application. (c) Show the additional code that must be added to the bufferPut function to make it work correctly (d) Condition variables are subject to spurious wakeup. How is this problem handled?Explanation / Answer
(a) We can create pthread condition variable using pthread_cond_t as
In order to initialize it, we use pthread_cond_init as
The first parameter is a pointer to our newly created pthread_cond_t and the second parameter is a pointer to attributes. We can create a default attribute and supply to it as
Also remember to destroy attribute and conditional variables using:
(b) We need to declare and initialize mutex variables. They could be done as:
The first parameter is a pointer to our newly created pthread_mutex_t and the second parameter is a pointer to attributes. Also remember to destroy mutex variables using:
(c) Code should be inserted in if statement like
if (count == BUFFERSIZE){
//Buffer is full, wait
//Here comes the code given below if statement
//Now unlock the mutex
}
(d) By using mutex and while loop as above.
Hope it Helps!