The behaviour depends on the kind of the mutex. The POSIX standard says that recursive locking behaviour depends on the type of the lock
If a thread attempts to relock a mutex that it has already locked, pthread_mutex_lock()
shall behave as described in the Relock column of the following table.
With the Relock column saying that
- a mutex of type
PTHREAD_MUTEX_NORMAL
can deadlock
- a mutex of type
PTHREAD_MUTEX_ERRORCHECK
shall return an error
- a mutex of type
PTHREAD_MUTEX_RECURSIVE
will work as a recursive lock, that you must then unlock as many times as you locked it
- a mutex of type
PTHREAD_MUTEX_DEFAULT
will have undefined behaviour, which actually means that if on that platform the default lock is of any of the previous 3 types, it will behave characteristically as in the columns above, and if it is some other type then the behaviour will be undefined.
Thus there is especially no point in testing a PTHREAD_MUTEX_DEFAULT
lock to find out what the behaviour is.
And the Linux manuals pthread_mutex_lock(3)
rephrases with the following:
If the mutex is already locked by the calling thread,
the behavior of pthread_mutex_lock depends on the
kind of the mutex. If the mutex is of the fast
kind, the calling thread is suspended until the mutex
is unlocked, thus effectively causing the calling
thread to deadlock. If the mutex is of the error
checking kind, pthread_mutex_lock returns immediately with the error code EDEADLK
. If the mutex is
of the recursive kind, pthread_mutex_lock
succeeds and returns immediately, recording the number
of times the calling thread has locked the mutex. An
equal number of pthread_mutex_unlock
operations must
be performed before the mutex returns to the unlocked
state.
In Linux according to the documentation, the default type is fast, but you cannot rely that to be portable.