...
/Better, But Still Broken: While, Not If
Better, But Still Broken: While, Not If
Let's try to work on the solution of the producer/consumer problem from the last lesson.
We'll cover the following...
In the last lesson, we saw how the solution we came up with for the producer/consumer problem did not work correctly for more than one consumer due to the race condition. Fortunately, fixing it is easy (see the code excerpt below): change the if
to a while
.
Press + to interact
int loops; // must initialize somewhere...cond_t cond;mutex_t mutex;void *producer(void *arg) {int i;for (i = 0; i < loops; i++){Pthread_mutex_lock(&mutex); // p1if (count == 1) // p2Pthread_cond_wait(&cond, &mutex); // p3put(i); // p4Pthread_cond_signal(&cond); // p5Pthread_mutex_unlock(&mutex); // p6}}void *consumer(void *arg) {int i;for(i = 0; i < loops; i++) {Pthread_mutex_lock(&mutex); // c1while (count == 0) // c2Pthread_cond_wait(&cond, &mutex); // c3int tmp = get(); // c4Pthread_cond_signal(&cond); // c5Pthread_mutex_unlock(&mutex); // c6printf("%d\n", tmp);}}
Why this works?
Think about why this works; now consumer ...
Access this course and 1400+ top-rated courses and projects.