POSIX thread exit/crash/exception-crash while holding mutex

て烟熏妆下的殇ゞ 提交于 2019-12-07 03:16:57

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7348465/posix-thread-exit-crash-exception-crash-while-holding-mutex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!