11

Several processes access shared memory, locking it with the mutex and pthread_mutex_lock() for synchronization, and each process can be killed at any moment (in fact I described php-fpm with APC extension, but it doesn't matter).
Will the mutex be unlocked automatically, if the process locked the mutex and then was killed?
Or is there a way to unlock it automatically?

Edit: As it turns out, dying processes and threads have similar behavior in this situation, which depends on robust attribute of mutex.

fadimko
  • 113
  • 1
  • 6
  • 4
    It depends on the type of mutex being used, which you didn't specify. Punch [robust mutex](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_setrobust.html) into your favorite search engine. – David Schwartz Sep 29 '14 at 16:53
  • 2
    Please see [this related question](http://stackoverflow.com/questions/7348465/posix-thread-exit-crash-exception-crash-while-holding-mutex) and as David said look into robust mutexes. They don't get unlocked after a crash, but the next thread that will attempt to lock it will receive a `EOWNERDEAD` error code. – user703016 Sep 29 '14 at 16:54
  • It would be nice to make an answer out of that, but David's comment is probably too terse to be an answer as-is. – R.. GitHub STOP HELPING ICE Sep 29 '14 at 17:32
  • I'd consider this question being a duplicate to the question linked by *Cicada*'s comment. It's been answered by you there? @R.. – alk Sep 30 '14 at 10:23
  • @DavidSchwartz, thank you, robust mutexes is what I looked for. – fadimko Sep 30 '14 at 14:21
  • @Cicada, I thought, that dying processes and threads should behave differently, so I didn't read this question. Thank you! – fadimko Sep 30 '14 at 14:26

1 Answers1

2

That depends on the type of mutex. A "robust" mutex will survive the death of the thread/process. See this question: POSIX thread exit/crash/exception-crash while holding mutex

The next thread that will attempt to lock it will receive a EOWNERDEAD error code

Note: Collected information from the comments.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820