CrazyC
CrazyC

Reputation: 1896

Thread crashed with locked Mutex

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

Upvotes: 6

Views: 5968

Answers (3)

Gabe
Gabe

Reputation: 86718

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.

Upvotes: 5

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

That certainly depends on (at least) two things:

  • How the mutex is implemented, and
  • How the thread crashes (does it throw an exception, or does it just "disappear").

For instance, in Java's synchronized blocks are guaranteed to be released when the "thread is done with the object" - whatever that means (see link). According to this article:

Stopping a thread causes it to unlock all the monitors that it has locked.

Ok, stop()ing the thread releases the monitors, but what if a thread just somehow disappears, is it then "done with the object"? I don't see this documented anywhere. But it's obvious that someone must release locked mutexes, or otherwise they'll deadlock; perhaps some mutexes or environments include mechanisms that release mutexes automatically if the thread, who locked them, becomes nonexistent.

Another example: java.util.concurrent.Lock docs recommend using a finally statement to release the lock so that whatever happens with the executing thread, the lock would get released. But, if the thread disappears before that finally statement gets executed, then the lock never gets released and a deadlock indeed occurs. Of course, threads shouldn't "disappear" just like that.

Quite a good question!

Upvotes: 2

CrazyC
CrazyC

Reputation: 1896

Thanks for your response. http://msdn.microsoft.com/en-us/library/ms687032%28VS.85%29.aspx MSDN also says it release the mutex and waiting threads get the WAIT_ABANDONED status.

Upvotes: 0

Related Questions