Automatically release mutex on crashes in Unix

a 夏天 提交于 2020-01-15 04:24:26

问题


I have two programs interacting via a shared memory segment. When using the segment for read or write, they hold a lock.

Should either of them crash (get killed, typically - possibly with something untrappable) in a critical section, I would like them to release the lock so that the shmem isn't locked out completely.

Other questions point the way to the answer in Windows, Java, etc. but how do you do it in Unix (and specifically Linux)?

(I'm not attached to the pthreads mutex functions; SysV semaphores or anything else will do just fine.)


回答1:


I believe POSIX robust mutexes are what you're looking for:

http://www.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_getrobust.html




回答2:


I think this is by design. If one of the processes crashed, it's likely that the critical section being locked for got interrupted and the data stored in that shared memory segment is inconsistent, invalid, or unsafe. Accessing the memory and operating as though nothing happened from the other process could very well make it crash or worse, depending on what it does.




回答3:


System V semaphores support the SEM_UNDO option to do exactly this. However, unlike robust mutexes this will not notify the next thread to acquire the lock. On the upside, they are more portable than robust mutexes.



来源:https://stackoverflow.com/questions/4149266/automatically-release-mutex-on-crashes-in-unix

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