There is scenario, I have two threads both are using same mutex. One thread locked the mutex and crashed. What would be the mutex state? Is it still locked and second thread never own that mutex? Means a deadlock situation?
Edit - Also explain a case of pthread on Linux systems
The mutex is either in a locked or unlocked state for a thread. If a thread attempts to relock a mutex that it has already locked, it will return with an error. If a thread attempts to unlock a mutex that is unlocked, it will return with an error.
Deadlock! If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into waiting list of that mutex which results in deadlock.
A problem exists if two threads attempt to claim both resources but lock the associated mutexes in different orders. For example, if the two threads lock mutexes 1 and 2 respectively, a deadlock occurs when each attempts to lock the other mutex.
If the mutex is already locked by another thread, the subroutine blocks the calling thread until the mutex is unlocked. If the mutex is already locked by the calling thread, the subroutine might block forever or return an error depending on the type of mutex.
Since you haven't specified what OS, I'll tell you what happens in Win32.
In Win32, the second thread would get WAIT_ABANDONED when it goes to wait on the mutex owned by a thread that has terminated. Note that receiving WAIT_ABANDONED means the second thread has received the mutex, so there won't be a deadlock. The second thread should detect the WAIT_ABANDONED result and verify that the resource protected by the mutex is in a valid state. If it can detect corruption and does not detect any, it is safe to proceed. If not, it's a good idea to raise an error of some sort.
With some implementations of a mutex there is no way to detect that the thread owning it has terminated, and you end up with a deadlock.
With some implementations of a mutex there is a way to detect what the owning thread is, figure out that the owning thread has terminated, and then take ownership of the mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With