. .
Depending upon your program, you may wish to wake up all the threads that are waiting on a
condition. Perhaps they were all waiting for the right time of day to begin background work or
were waiting for a certain network device to become active. A pthread_cond_broadcast()
is used exactly like pthread_cond_signal() (Code Example 6-14). It is called after some
aspect of the condition has changed. It then wakes all of the sleeping threads (in an undefined
order), which then must all hurry off to reevaluate the condition. This may cause some contention
for the mutex, but that's OK.
Example 6-14 Using a Condition Variable (POSIX)
Thread 1
Thread 2
while (!my_condition)
pthread_cond_wait(&c, &m);
... sleeping ...
my_condition = TRUE;
/* pthread_cond_broadcast(&c); */
Presumably you are calling signal or broadcast any time that the condition has been changed such
that it may have become true. In most cases you will have evaluated the condition completely
before you signal or broadcast, but you do not have to. You certainly would want to signal any
time that the condition became true.
There are several things you can do with condition variables that the compiler won't complain
about but are guaranteed trouble. You could use the same condition variable with different
mutexes (some POSIX implementations will detect this at runtime). You could have several
functions that use one condition variable but that evaluate different conditions. (This latter is not
illegal and is sometimes even useful, but not very often.) Be careful!
Java wait/notify
The Java equivalent to condition variables is wait/notify (Code Example 6-15). The behavior is
virtually identical. You enter a synchronized section, evaluate a condition, continue on if true, and
wait (releasing the synchronized section) if not. Another thread will enter a synchronized section,
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks