I have below code where function bar lock the mutex and then called function foo, however function foo lock the same mutex. according to my understanding, dead-lock will take place because foo are trying to lock the same mutex and it has been locked in function bar. But below code executes without any halt. Who knows the reason??
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void foo()
{
pthread_mutex_lock(&mutex);
cout<<"excuting foo!!"<<endl;
pthread_mutex_unlock(&mutex);
}
void bar()
{
pthread_mutex_lock(&mutex);
cout<<"excuting bar!!"<<endl;
foo();
pthread_mutex_unlock(&mutex);
}
int main()
{
bar();
}
The POSIX thread specification allows a POSIX thread implementation to use any of the standard three mutex types as the default one:
If the mutex type is PTHREAD_MUTEX_DEFAULT, the behavior of pthread_mutex_lock() may correspond to one of the three other standard mutex types
What is PTHREAD_MUTEX_DEFAULT
? That's pretty much what you expect:
The default value of the type attribute is PTHREAD_MUTEX_DEFAULT.
...
An implementation may map PTHREAD_MUTEX_DEFAULT to one of the other mutex types.
You are expecting your mutex to be PTHREAD_MUTEX_NORMAL
which will cause a deadlock here. However, your particular thread implementation appears to be the PTHREAD_MUTEX_RECURSIVE
type, which can be locked more than once by the same process. This is the behavior you are observing.