OSF DCE Application Development Guide--Core Components

OSF DCE Application Development Guide—Core Components
The following subsections discuss the use of mutexes to prevent two potential problems:
race conditions and deadlocks. Also discussed is why you should signal a condition
variable with the associated mutex locked.
8.6.1 Race Conditions
A race condition occurs when two or more threads perform an operation, and the result
of the operation depends on unpredictable timing factors; specifically, when each thread
executes and waits and when each thread completes the operation.
An example of a race condition is as follows:
1. Both A and B are executing (X = X + 1).
2. A reads the value of X (for example, X = 5).
3. B comes in and reads the value of X and increments it (making X = 6).
4. A gets rescheduled and now increments X. Based on its earlier read operation, A
thinks (X+1 = 5+1 = 6). X is now 6. It should be 7 because it was incremented
once by A and once by B.
To avoid race conditions, ensure that any variable modified by more than one thread has
only one mutex associated with it. Do not assume that a simple add operation can be
completed without allowing another thread to execute. Such operations are generally
not portable, especially to multiprocessor systems. If it is possible for two threads to
share a data point, use a mutex.
8.6.2 Deadlocks
A deadlock occurs when one or more threads are permanently blocked from executing
because each thread waits on a resource held by another thread in the deadlock. A
thread can also deadlock on itself.
The following is one technique for avoiding deadlocks:
1. Associate a sequence number with each mutex.
2. Lock mutexes in sequence.
3. Do not attempt to lock a mutex with a sequence number lower than that of a
mutex the thread already holds.
Another technique, which is useful when a thread needs to lock the same mutex more
than once before unlocking it, is to use a recursive mutex. This technique prevents a
thread from deadlocking on itself.
8 12 Tandem Computers Incorporated 124245