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
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.