Information Technology Reference
In-Depth Information
Add loops to wait using the condition variable(s)
Add signal() and broadcast() calls
We will talk about each of these issues in turn.
Other than these fairly-mechanical changes, writing the rest of the code for
your proceeds as it does in the single-threaded case.
5.6.2
Add a lock
Add a lock as a member variable for each object in the class to enforce mutual
exclusion on access to each object's shared state.
Note that in this chapter, we focus on the simple case where each shared
object includes exactly one lock. Later, we will talk about more advanced varia-
tions such as an ownership design pattern where higher-level program structure
enforces mutual exclusion by ensuring that at most one thread at a time owns
and can access an object and fine grained locking where a single object may
subdivide its state into multiple parts, each protected by its own lock.
5.6.3
Acquiring and releasing the lock
All code that accesses the object's state that is shared across more than one
thread must hold the object's lock. Typically, all of an object's member variables
are shared state.
The simplest and most common thing to do is to acquire the lock at the start
of each public method and release it at the end of each public method. If you
do this, it is easy to inspect your code to verify that a lock is always held when
needed. Also, if you do this, then the lock is already held when each private
method is called, and you don't need to reacquire it.
Warning. You may be tempted to try to avoid acquiring the lock in some
methods or some parts of some methods. Do not be tempted by this \optimiza-
tion" until you are a very experienced programmer and have done sucient
profiling of the code to verify that the optimization you are considering will
significantly speed up your program.
Remember that acquiring an uncontended lock is a relatively inexpensive
operation. Also, remember from the Too Much Milk problem that reasoning
about memory interleavings can be quite dicult|and the instruction reorder-
ing done by modern compilers and processors makes it even harder. The sidebar
discusses one commonly used (and abused) \optimization."
 
Search WWH ::




Custom Search