Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On linux, how to make sure to unlock a mutex which was locked in a thread that dies/terminates?

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

like image 600
user1002288 Avatar asked Dec 02 '22 23:12

user1002288


1 Answers

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. It is set using the POSIX.1-2008 standard function pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST).

Further details and example code can be found on the Linux manual page for pthread_mutexattr_getrobust.

like image 136
mark4o Avatar answered Dec 27 '22 21:12

mark4o