

There are an infinity of ways of writing code that doesn't halt. The POSIX documentation has a table of the behaviors of all three, and you'll notice that the behavior for relocking a normal mutex is explicitly that the thread should deadlock. That takes care of the multuple lock/unlock problem. Third is the recursive mutex, which keeps count of the number of times it was locked by the same thread and requires a corresponding number of unlocks before the mutex is released. (That would be avoided by not unlocking if the lock failed because the mutex was already locked.) The thread's code can decide to proceed if a second attempt is okay, but there's the danger that what made the second call could also call unlock() and leave critical part vulnerable to alteration by another thread. Second is the error-checking mutex, which averts self-deadlock by treating attempted re-locking as an error and returning control to the thread. Because of this hazard, development guidelines tend to recommend not using normal mutexes.
#THREAD DEADLOCK HOW TO#
This is how to produce a deadlock within one thread, making what you ask about technically possible. Since it's the same thread, that will never happen and the thread will have effectively deadlocked itself. The second call to lock() will wait on the thread that locked m to unlock it. The majority of operating systems that support threading conform to POSIX, which defines defines three types of mutexes:įirst is the normal mutex, which is the classic implementation that will wait for an unlock no matter who locked it: Mutex m(NORMAL) This is a good base for a general discussion, but it overlooks the practical reality that some implementations of mutexes behave differently in the face of contention and don't care about that technicality. Wikipedia's definition of a deadlock requires that there be multiple processes (or threads) holding the right set of resources for one to occur. I am not posting this code since I know it would be off-topic for this site. I tried to create a deadlock with one thread in C#, where condition 4 may not literally be met, but it still looks like a deadlock to me.
