Information Technology Reference
In-Depth Information
SharedObject::someMethodThatSignals()
{
lock.acquire();
//...readand/orwritesharedstatehere...
//Ifstatehaschangedinawaythatcould
//allowanotherthreadtomakeprogress,
//signal(orbroadcast).
cv.signal();
lock.release();
}
Figure5.8: Design pattern for a method that signal() 's using a condition
variable. The pattern for broadcast() is similar.
a condition variable will work as shown in Figure 5.7. In this code, the calling
thread rst acquires the lock and then can read and write the shared object's
state variables. To wait until testOnSharedState() passes, the thread calls
wait() on the shared object's condition variable cv . Later, once the calling
thread runs again and sees testOnSharedState() pass, it can do whatever it
is it wants to do, release the lock, and return.
Figure 5.8 shows complementary code that changes the shared object's state
in a way that might allow a waiting thread to make progress and then signals
that thread with the condition variable.
Condition variables integrate with locks. Notice that a waiting thread
is always waiting for the state of a shared object to change, so it must inspect
the object's state in a loop. So, the condition variable's wait() method releases
the lock (to let other threads change the state of interest) and then reacquires
the lock (to check that state again.)
Similarly, the only reason for a thread to signal() (or broadcast() ) is that
it just changed the state in a way that may be of interest to a waiting thread.
In order to make such a change to shared state, the thread must hold the lock,
so signal() and broadcast() are always called while holding a lock on the
state that was just changed.
Discussion. As just indicated, condition variables have been carefully de-
signed to work in tandem with mutual exclusion locks and shared state. The
precise definition of condition variables therefore includes three properties worth
additional comment:
1. A condition variable is memoryless; the condition variable, itself, has no
internal state other than a queue of waiting threads.
Condition variables do not need state of their own because they are always
used within shared objects that define their own state. Condition variables
 
Search WWH ::




Custom Search