Information Technology Reference
In-Depth Information
SharedObject::someMethodThatWaits()
{
lock.acquire();
//...readand/orwritesharedstatehere...
while(!testOnSharedState()){
cv.wait(&lock);
}
assert(testOnSharedState());
//...readand/orwritesharedstatehere...
lock.release();
}
Figure5.7: Design pattern for a method that
wait()
's using a condition
variable.
expected each request to take a few milliseconds but instead each request was
taking half a second. Fortunately, the performance was so horrible that it was
easy to track down the problem: layers were passing work to each other through
queues much like the
TSQueue
shown above, and
remove()
was implemented as
a polling loop with a 100ms delay. With five such layers of processing, the server
became unusably slow. Fortunately, the fix was simple: use condition variables,
which we will now define.
5.4.1
Condition variable definition
A condition variable is a synchronization object that enables a thread to e-
Definition: condition
variable
ciently wait for a change to shared state that is protected by a lock. A condition
variable has three methods:
CV::wait(Lock*lock)
atomically releases the lock and suspends execu-
tion of the calling thread, placing the calling thread on the condition vari-
able's
waitingqueue
. Later, when the calling thread is reenabled, it
reacquires the lock before returning from the
wait()
call.
CV:signal()
takes one waiting thread o the condition variable's
waiting
queue
and marks it as eligible to run (i.e., it puts the thread on the
scheduler's ready list.)
CV::broadcast()
takes all waiting threads o the condition variable's
waitingqueue
and marks them as eligible to run.
Notice that a condition variable is always associated with a lock. One uses
a condition variable to wait for a change to shared state, and updates to shared
state are protected with a lock. Thus, the condition variable API is carefully
designed to work in concert with mutual exclusion locks.
In particular, the standard design pattern is for a shared object to include
a lock and zero or more condition variables. Then, a method that waits using