pthread process shared mutex deadlock

823 views Asked by At

I use process shared pthread_mutex_t on shared memory. I wonder what if a process lock the mutex and somehow exit, what will happen? As my experiment shows, deadlock happens, but this is a bad news. So is there a way to prevent this? Should not the mutex automatically unlocked when process exit?

1

There are 1 answers

2
caf On

No, the mutex shouldn't be automatically unlocked, because the shared data protected by the mutex may be in an inconsistent state.

If you want to handle this situation, you need to use "robust mutexes". To create a robust mutex, set the mutex robustness property to PTHREAD_MUTEX_ROBUST by using pthread_mutexattr_setrobust() on a pthread_mutexattr_t object that is used to initialise the mutex.

If a thread or process exits while holding a robust mutex, the next call to pthread_mutex_lock() on that mutex will return the EOWNERDEAD error. If this error is returned, your code must carefully check all the shared state protected by the mutex and fix any inconsistencies. It can then mark the state as consistent by calling pthread_mutex_consistent() on the mutex, and then continue its execution as normal.