
How would you use condition variables to wait for two resources to become available?


See "Principles of Parallel Programming", by Lin & Snyder, page 159.

See Matthew Flatt, Univ of Utah, CS 4960, sample-midterm1.pdf

http://www.eng.utah.edu/~cs4960-01/sample-midterm1.pdf


There are several things wrong with this "consumer" code.

EatJuicyFruit()
{
   pthread_mutex_lock(&lock);
     while (apples==0 || oranges==0)
     {
        pthread_cond_wait(&more_apples, &lock);
        pthread_cond_wait(&more_oranges, &lock);
     }
     /* Critical Section: Eat both an apple and an orange */
   pthread_mutex_unlock(&lock);
}


This does not work either (Lin & Snyder, page 160).

EatJuicyFruit()
{
   pthread_mutex_lock(&lock);
     while (apples==0)
     {
        pthread_cond_wait(&more_apples, &lock);
     }
     while (oranges==0)
     {
        pthread_cond_wait(&more_oranges, &lock);
     }
     /* Critical Section: Eat both an apple and an orange */
   pthread_mutex_unlock(&lock);
}


Here are the produces.

MakeApple()
{
   MakeAnApple();
   pthread_mutex_lock(&lock);
     apple++;
     pthread_sig_cv(&more_apples);
   pthread_mutex_unlock(&lock);
}

MakeOrange()
{
   MakeAnOrange();
   pthread_mutex_lock(&lock);
     orange++;
     pthread_sig_cv(&more_oranges);   
   pthread_mutex_unlock(&lock);
}



Here is a solution from Matthew Flatt.

EatJuicyFruit()
{
   pthread_mutex_lock(&lock);
     while (apples==0 || oranges==0) 
     {
        if (apples == 0)
           pthread_cond_wait(&more_apples, &lock);
        if (oranges == 0)
           pthread_cond_wait(&more_oranges, &lock);
     }
     /* Critical Section: Eat both an apple and an orange */
     apple--;
     orange--;   
   pthread_mutex_unlock(&lock);   
}   




Here is a proposed solution that uses a single condition variable.

EatJuicyFruit()
{
   pthread_mutex_lock(&lock);
     while (apples==0 || oranges==0)  // we need BOTH an apple and an orange
     {
        pthread_cond_wait(&more_oranges_or_apples, &lock);
     }
     /* Critical Section: Eat both an apple and an orange */
     apple--;
     orange--;
   pthread_mutex_unlock(&lock);
}


MakeApple()
{
   MakeAnApple();
   pthread_mutex_lock(&lock);
     apple++;
     pthread_sig_cv(&more_oranges_or_apples);
   pthread_mutex_unlock(&lock);
}

MakeOrange()
{
   MakeAnOrange();
   pthread_mutex_lock(&lock);
     orange++;
     pthread_sig_cv(&more_oranges_or_apples);   
   pthread_mutex_unlock(&lock);
}



NOTE: The above solutions only bound the "consumer" thread, 
      they do not bound the producers. How would you also
      bound the producers so that they do not overflow the
      apple and orange containers?