Information Technology Reference
In-Depth Information
When waiting upon a Condition, a \spurious wakeup" is permit-
ted to occur, in general, as a concession to the underlying platform
semantics. This has little practical impact on most application pro-
grams as a Condition should always be waited upon in a loop, testing
the state predicate that is being waited for. An implementation is
free to remove the possibility of spurious wakeups but it is recom-
mended that applications programmers always assume that they can
occur and so always wait in a loop.
(From http://download.oracle.com/docs/cd/E17476_01/javase /
1.5.0/docs/api/index.html )
Modularity: Waiting in a loop that checks the shared state makes shared
objects' code more modular because we can reason about when the thread will
continue by looking just at the wait() loop; in particular, we do not need to
examine the rest of the shared object's code to understand where and why calls
to signal() and broadcast() are done to know the postcondition for wait()
loop. For example, in Figure 5.7, we know the assert() call will never fail
without having to look at any other code.
Not only does always waiting in a loop simplify writing and reasoning about
the code that waits, it simplifies writing and reasoning about the code that
signals or broadcasts because you never have to worry that signaling at the
wrong time will cause a waiting thread to proceed when it shouldn't. Signal()
and broadcast() can be regarded as hints that it might be a good time to try
to proceed, but if the hints turn out to be wrong, no damage is done. You
can always convert a signal() to a broadcast() add any number of signal()
or broadcast() calls without changing the semantics of the object. Avoiding
extra signal() and broadcast() calls may matter for performance, but not
for correctness.
Bottom line: Given the range of implementations that are possible and
given the modularity benefits, wait() must always be done from within a loop
that tests the desired predicate.
5.4.2
Thread life cycle revisited
In Chapter 4 on page 152, we discussed how a thread can switch between the
Ready,Waiting, andRunningstates.
We can now explain theWaiting
state in more detail.
ARunningthread that calls Cond::wait() is put in theWaitingstate.
This is typically implemented by moving the thread's thread control block
(TCB) from the scheduler's ready queue to a queue of waiting threads asso-
ciated with that condition variable. Later, when some otherRunningthread
calls Cond::signal() or Cond::broadcast() on that condition variable, one (if
Search WWH ::




Custom Search