Reference no: EM132329178
Suppose we have two threads, in a producer/consumer arangement 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 string values:
#define BUFFERSIZE 50
char* 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 in the buffer
Here is the code for the bufferPut function:
void bufferPut(char* data)
{
pthread_mutex_lock(&lock);
while( count==BUFFERSIZE ){
pthread_cond_wait(¬Full,&lock)
}
buffer[inIndex]= data;
inIndex++;
if( inIndex==BUFFERSIZE ){
inIndex= 0; }
count++;
pthread_signal(¬Empty);
pthread_mutex_unlock(&lock);
}
(The bufferGet function looks very similar.)
(a) In the bufferPut function, why is mutex variable named lock? needed?
(b) When count == BUFFERSIZE, the buffer is full. In this situation, the bufferPutfunction calls pthread cond wait. Explain what pthread cond wait does.
(c) Why does the call to pthread cond wait need to be passed the mutex lock variablelock?
(d) Why is the call to pthread cond wait contained within a while loop, and instead of within a simple if statement?