One of the potential pitfalls in using mutexes is the so-called deadly embrace. This is an
undesirable situation in which two or more threads become suspended indefinitely while
attempting to get mutexes already owned by other threads. Figure 7.13 illustrates a scenario
that leads to a deadly embrace. Following is the sequence of events depicted in this figure.
- Thread 1 obtains ownership of Mutex 1
- Thread 2 obtains ownership of Mutex 2
- Thread 1 suspends because it attempts to obtain ownership of Mutex 2
- Thread 2 suspends because it attempts to obtain ownership of Mutex 1
Thus, Thread 1 and Thread 2 have entered a deadly embrace because they have suspended
indefinitely, each waiting for the mutex that the other thread owns.
How can you avoid deadly embraces? Prevention at the application level is the only
method for real-time systems. The only way to guarantee the absence of deadly
embraces is topermit a thread to own at most one mutex at any time. If threads must
own multiple mutexes, you can generally avoid deadly embraces if you make the threads
gather the mutexes in the same order. For example, the deadly embrace in Figure 7.13
could be prevented if the threads would always obtain the two mutexes in consecutive
order, i.e., Thread 1 (or Thread 2) would attempt to acquire Mutex 1, and then would
immediately attempt to acquire Mutex 2. The other thread would attempt to acquire
Mutex 1 and Mutex 2 in the same order.
One way to recover from a deadly embrace is to use the suspension time-out feature
associated with the tx_mutex_get service, which is one of the three available wait
options. Another way to recover from a deadly embrace is for another thread to invoke
the tx_thread_wait_abort service to abort the suspension of a thread trapped in a
deadly embrace.
Note:Deadly Embrace problem is also associated with the use of semaphores.