Reputation: 141
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();
}
Upvotes: 1
Views: 120
Reputation: 157
You need to modify bar() as:
void bar()
{
pthread_mutex_lock(&mutex);
cout<<"excuting bar!!"<<endl;
pthread_mutex_unlock(&mutex);
foo();
}
In your code, deadlock is there because sequence is following 1. bar () locks mutex, 2. Foo() trying to lock mutex again which is already locked by bar 3. bar() unlocks it,but earlier operation step 2, still waiting for mutex. This steps waits for step 2 to finish
Upvotes: 0
Reputation: 118292
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.
Upvotes: 2