Appendices > Portable Thread Library > Condition Variables > Waiting for a Condition Variable
 
Waiting for a Condition Variable
A call to the member function wait causes one or more threads to wait for the condition variable. These threads can then be woken up by another thread through a call to the member function broadcast, which releases any waiting threads and then reblocks the condition variable. Hence, if the member function broadcast is invoked before the other thread has called the member function wait, then the thread will never be released.
A thread can call the broadcast member function as many times as it wants. It is not an error to call the member function broadcast if there are no waiting threads.
The following example shows a thread that is waiting for a condition variable created with a private mutex. Hence, the application has to lock the mutex before calling the wait method:
static IlsUnsafeMutex mutex;
static int count=0;
static IlsCond cond(&mutex);
 
mutex.lock();
while (count>3) {
  // wait until count gets to 3 or more
  cond.wait();
}
mutex.unlock();
Note: If the mutex is private, it is relocked before the member function “wait”S exits. Thus, it is necessary to unlock the mutex once the loop finishes. Also, the member function wait will atomically unlock the mutex before going into the wait state so that the thread that calls the member function “broadcast” can safely lock the mutex before invoking that member function and incrementing the counter.
...
mutex.lock();
count++;
cond.broadcast();
mutex.unlock();
...
The following example shows a simple case in which the mutex is not provided. In this case, the code just calls wait on the condition variable and the mutex is called by the condition variable itself:
static IlsCond cond;
 
// now wait for someone to broadcast the condition variable
cond.wait();

Version 6.3
Copyright © 2018, Rogue Wave Software, Inc. All Rights Reserved.