...
/The Single Buffer Producer/Consumer Solution
The Single Buffer Producer/Consumer Solution
This lesson fixes the problem we saw in the solution in the last lesson.
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.
Press + to interact
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 ...