Once again, no thread may hold a pointer to any portion of the list unless it owns one of the locks.
If it only holds a local salary lock, it may not do anything except access that one data item. As
soon as the element is removed from the list (see Code Example 12-5), we can release the RWlock
(no one else will ever be able to access our item).
In this code, the only points of contention are:
Only one liquidator at a time may search.
Only one thread at a time may give a raise to a given individual.
Something that you might consider at this point is: Why not allow multiple liquidators to search at
the same time, then once they've found the object, convert the read lock into a write lock? We
could modify the definition of RWlocks to allow this possibility; however, it wouldn't work. We
would have to ensure that only one thread ever wanted to make the conversion at a time, and as
soon as it made that request, every other thread with a read lock would eventually have to release
that lock without making a conversion request. In other words, it's possible to do, but it's so
limited in functionality as to be nearly worthless.
For pretty much any program of this nature, design 3 will turn out to be the best. However, there
are other possibilities.
One Local Lock
What if we allocated one mutex per element to protect only one element? In Figure 12-8, each
mutex protects a pointer and the structure to which the pointer points. (The global mutex protects
only the global pointer and first structure.) With this design, multiple threads may search down the
list at the same time, either to update a salary or to remove an element. Now, multiple liquidator
threads may search and destroy simultaneously! Unfortunately, as soon as one thread finds the
element it is searching for, it will continue to hold the lock while it finishes its work. Other threads
will quickly pile up behind it, waiting to acquire that mutex. This design yields abysmal results
for every combination of CPUs, threads, list length, delay times, etc.
Ever drive 101 at rush hour?
Figure 12-8. Friends/Enemies with Only One Local Mutex Lock
Search WWH :