Search⌘ K

The Single Buffer Producer/Consumer Solution

Explore the single buffer solution to the classic producer consumer problem by understanding how to use two condition variables for directed signaling. Learn why while loops are essential for waiting on conditions to avoid spurious wakeups. Discover how this method improves concurrency and efficiency by controlling when producers or consumers sleep based on buffer state.

We'll cover the following...

As we discussed in the last lesson, we clearly need to have directed signalling i.e. a consumer should only wake up a producer and vice versa. The solution here is once again a small one: use two condition variables, instead of one, in order to properly signal which type of thread should wake up when the state of the system changes. The code excerpt below shows the resulting code.

C
cond_t empty, fill;
mutex_t mutex;
void *producer(void *arg) {
int i;
for(i=0;i<loops;i++){
Pthread_mutex_lock(&mutex);
while (count == 1)
Pthread_cond_wait(&empty, &mutex);
put(i);
Pthread_cond_signal(&fill);
Pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg) {
int i;
for (i=0;i<loops;i++){
Pthread_mutex_lock(&mutex);
while (count == 0)
Pthread_cond_wait(&fill, &mutex);
int tmp = get();
Pthread_cond_signal(&empty);
Pthread_mutex_unlock(&mutex);
printf("%d\n", tmp);
}
}

In the code, producer threads wait on the condition empty, and signals fill. Conversely, consumer threads wait on fill and signal empty. By doing so, the second problem ...