6

Is there a well defined behavior for POSIX mutex ownership in case of

  1. Thread exits
  2. Thread crashes
  3. Thread crashes due to exception

Suppose thread-1 owns a mutex. And thread-2 is waiting to acquire the same mutex. And thread-1 goes the 1/2/3 scenario. What is the effect on thread-2 ?

PS : I believe the behavior for spin-lock is, NOT to unblock thread-2, with reasoning that the section protected by spin-lock is in bad shape anyways.

Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79
  • it remains locked. This is c, so the runtime doesn't do anything for you, so if you don't unlock it yourself it stays locked. – Kevin Sep 08 '11 at 14:08

2 Answers2

8

If you're worried about these issues, Robust Mutexes may be the tool you're looking for:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_setrobust.html

After a thread that owns a robust mutex terminates without unlocking it, the next thread that attempts to lock it will get EOWNERDEAD and become the new owner. This signals that it's responsible for cleaning up the state the mutex protects, and marking it consistent again with the pthread_mutex_consistent function before unlocking it. Unlocking it without marking it consistent puts the mutex in a permanently unrecoverable state.

Note that with robust mutexes, all code that locks the mutex must be aware of the possibility that EOWNERDEAD could be returned.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 1
    But be extra careful when `EOWNERDEAD` is returned -- any data structures protected by the mutex will likely be in an inconsistent state. See [Understanding the consequences of WAIT_ABANDONED](http://blogs.msdn.com/b/oldnewthing/archive/2005/09/12/463977.aspx) for a more detailed discussion (although that refers to Windows mutexes, which have slightly different semantics from pthreads mutexes, but the main points of the post still hold). – Adam Rosenfield Sep 08 '11 at 14:44
  • 1
    Also, note that the documentation says that "If the owning thread of a robust mutex terminates while holding the mutex lock, the next thread that acquires the mutex **may** be notified about the termination by the return value [EOWNERDEAD]" (emphasis mine) -- it is not *guaranteed* to return `EOWNERDEAD`. Only in the case of when the *process* holding the mutex is terminated does it say that it *shall* return `EOWNERDEAD` (in which case it would have to be a process-shared mutex). – Adam Rosenfield Sep 08 '11 at 15:11
  • Thank you for your second comment. That's a really important detail I was not aware of. It's also worth noting that an implementation is not even required to support the robust attribute for non-process-shared mutexes. – R.. GitHub STOP HELPING ICE Sep 08 '11 at 15:51
1

It's really simple. If you don't explicitly unlock the mutex, it remains locked, regardless of what happened or why. This is c, not ruby on rails or visual basic.

Kevin
  • 24,871
  • 19
  • 102
  • 158