问题
This is an interview question.
On linux, how to make sure to unlock a POSIX mutex which was locked in a POSIX thread that dies/terminates?
My idea:
Linux will release it automatically when it send kill or termination signal to the program ? But, I cannot find more details about how OS do this ?
thanks
回答1:
A robust mutex can be used to handle the case where the owner of the mutex is terminated while holding the mutex lock, so that a deadlock does not occur. These have more overhead than a regular mutex, and require that all clients locking the mutex be prepared to handle the error code EOWNERDEAD
. This indicates that the former owner has died and that the client receiving this error code is the new owner and is responsible for cleaning up any inconsistent state.
A robust mutex is a mutex with the robust attribute set. On Linux this can be set using pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_NP)
, or using the POSIX standard function pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST) if you have glibc 2.12 or later (this function was standardized in POSIX.1-2008).
回答2:
If it's not a process-shared mutex, it doesn't matter. When one thread dies, the process dies, and the mutex goes away.
If it's a process-shared mutex, you're asking the wrong question. You wouldn't want to unlock the mutex if a thread died while holding it. The reason a thread holds a mutex is so that it can manipulate shared data through states that must not be seen by other threads. If a thread dies while holding a mutex, it is likely that the data was left in such an inconsistent state. Unlocking the mutex would just allow other threads to see the invalid/corrupt data.
来源:https://stackoverflow.com/questions/9198799/on-linux-how-to-make-sure-to-unlock-a-mutex-which-was-locked-in-a-thread-that-d