img
. . . . . .
Figure 6-1. Mutex with Several Threads Sleeping on It
Note that the mutex doesn't know who owns it.[3] Because mutexes protect sections of code,[4] it is
not legal for one thread to lock a mutex and for another thread to unlock it. Depending upon the
library implementation, this might not result in a runtime error, but it is illegal. The locking may
occur in one function while the unlocking occurs in another; locks may overlap in their use (lock 2,
unlock 1, lock 3, unlock 2, etc.), but under no circumstances should you ever release a lock from
the wrong thread. If you think you need this kind of behavior, you should (1) think really hard
about what you're doing, and (2) look at semaphores. This problem does not arise with Java
synchronized sections, but we will be implementing a Mutex class a bit later for which this caveat
applies.
[3]
POSIX doesn't prevent a mutex from recording its owner, it just doesn't require it. Some
implementations can be much faster if ownership is not recorded.
[4]
To be more precise, a mutex protects itself. We trick it into protecting sections of code by placing
the lock and unlock functions judiciously. By restricting data access to those functions, we manage
to have mutexes protect our shared data, which is what we really want.
In the execution graph for mutexes shown in Figure 6-2, we see the timing behavior of locks. The
graph is shown for two threads on two CPUs, but for a uniprocessor the behavior will be identical,
save that there will be gaps in each time line as the CPU context switches. Those gaps will affect
neither the correctness of the code nor the probability of encountering race conditions in correctly
locked code (see Race Conditions).
Figure 6-2. Execution Graph of the Operation of a Mutex
Figure 6-3 and Code Example 6-4 show the proper way to use mutexes while putting items onto a
list (as thread 1 is doing) and taking them off (thread 2). Should two threads call remove() at the
same time, one of them will get mutex ownership while the other will have to go to sleep. When
the mutex is released, the sleeper will be awakened, but it is possible that either thread 1 or a third
thread could slip in at just the right instant and get the lock. In this case the new thread, instead of
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home