On linux, how to make sure to unlock a mutex that has been blocked in a thread that dies / ends?

This is an interview question.

On Linux, how to unlock a POSIX mutex that has been blocked in a POSIX thread that is dying / ending?

My idea:

Will Linux release it automatically when it sends a termination or termination signal to the program? But I can not find more information on how the OS does this?

thanks

+4
source share
2 answers

A robust mutex can be used to handle the case where the owner of the mutex terminates while holding the mutex lock so that no deadlock occurs. They have more overhead than a regular mutex, and require that all clients blocking the mutex be prepared to handle the EOWNERDEAD error EOWNERDEAD . This indicates that the previous owner is dead and the client who received this error code is the new owner and is responsible for clearing any inconsistent state.

A robust mutex is a mutex with a robust set of attributes. On Linux, this can be set using pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_NP) or using the standard POSIX function pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST) if you have glibc 2.12 or later .1 is newer.

+14
source

If it is not a mutex associated with the process, it does not matter. When one thread dies, the process dies and the mutex leaves.

If it is a mutex shared by a process, you are asking the wrong question. You would not want to unlock the mutex if the thread died holding it. The reason a thread supports a mutex is because it can manage shared data through states that should not be considered by other threads. If a thread dies while holding a mutex, it is likely that the data remained in such an inconsistent state. Unlocking the mutex will allow other threads to see invalid / corrupted data.

+4
source

Source: https://habr.com/ru/post/1395458/


All Articles