Information Technology Reference
In-Depth Information
The bottom line here is that there is no hard and fast rule for how many
condition variables to use in a shared object or selecting the conditions that map
to each condition variable. Selecting condition variables requires some thought,
and different designers may group blocking situations differently and end up
with different condition variables for a class. Like many other design decisions,
these decisions are a matter of programmer taste, judgement, and experience.
The point is that asking \When can this method wait" may help you identify
what is for you a natural way of thinking about the condition variables for a
shared object.
5.6.5
Waiting using condition variables
Add a while(...) f cv.Wait() g loop into each method that you just identied
as potentially needing to wait before returning.
Remember that every call to Condition::Wait() must be enclosed in a
while loop that tests an appropriate predicate|modern implementations al-
most invariably enforce Hansen semantics and often allow for spurious wake-
ups (a thread can return from Wait() even if no thread called Signal() or
Broadcast() . Therefore, a thread must always check the condition before
proceeding|even if the condition was true when the Signal() or Broadcast()
call occurred, it my no longer be true when the waiting thread resumes execu-
tion.
Modularity benefits. Notice that if you always wait in a while loop, your
code becomes highly modular. You can look at the code that waits and know
what is true when it proceeds without examining any other code or understand-
ing when calls to Signal() or Broadcast() are made. Even erroneous calls to
Signal() or Broadcast() will not change how the waiting code behaves.
For example, consider the assertion in the following code:
...
while(!workAvailable()){
cond.wait(&lock);
}
assert(workAvailable());
...
We know that the assertion holds by local inspection without knowing anything
about the more distant code that calls Signal() or Broadcast() .
Waiting in a while loop also makes the signal and broadcast code more
robust. Adding an extra Signal() or changing a Signal() to a Broadcast()
will not introduce bugs.
Hint: Top-down design. As you start writing your code, you may know
that a method needs to include a wait loop, but you may not know exactly
 
Search WWH ::




Custom Search