Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pthread_mutex_t in linux are reentrancy (if a thread tries to acquire a lock that it already holds, the request succeeds)

I am coming from Java , so i am familiar with synchronize and not mutex. I wonder if pthread_mutex_t is also reentrancy. if not is there another mechanism for this?

Thank you

like image 957
Avihai Marchiano Avatar asked Dec 07 '22 13:12

Avihai Marchiano


2 Answers

This depends on the mutex type, the default does no checking and an attempt to lock it more than once in the same thread results in undefined behavior. Read about it here.

You can create a mutex of type PTHREAD_MUTEX_RECURSIVE to be able to recursively lock it, which is done by providing a pthread_mutexattr_t with the desired mutex type to pthread_mutex_init

like image 68
nos Avatar answered Dec 09 '22 03:12

nos


According to the manual, you can declare a mutex object as PTHREAD_MUTEX_RECURSIVE:

If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex shall maintain the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count shall be set to one. Every time a thread relocks this mutex, the lock count shall be incremented by one. Each time the thread unlocks the mutex, the lock count shall be decremented by one. When the lock count reaches zero, the mutex shall become available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.

See also pthread_mutex_attr_settype.

like image 21
Tudor Avatar answered Dec 09 '22 03:12

Tudor