Reputation: 335
I have a problem.
I have a static mutex initialized and trying to lock it in all of my functions. I accidently forgot to unlock it in one of the functions, but it seems that there is no deadlock taking place when i call another function that also tries to acquire the mutex lock.
Can someone please explain me why is it this way that deadlock is not occuring?
Code explaining my scenario of problem:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void main(void)
{
func1(); // Mutex acquired initially but not released at end
func2(); // This function acquires mutex even though mutex was not released by func1();
}
void func1(void)
{
pthread_mutex_lock(&mutex);
printf("I am in func1\n");
//MUTEX NOT UNLOCKED
}
void func2(void)
{
pthread_mutex_lock(&mutex);
printf("I am in func2\n");
//MUTEX AGAIN NOT UNLOCKED
}
Can someone please explian me why is deadlock not taking place in func2() as mutex was not released in func1() ?
Upvotes: 1
Views: 2274
Reputation: 1629
http://linux.die.net/man/3/pthread_mutex_lock
If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behavior.
Your program has undefined behavior and so may suddenly output "Formatting root partition, chomp chomp"... who knows.
Upvotes: 1
Reputation: 9490
According to the specification, PTHREAD_MUTEX_INITIALIZER is equivalent to a default mutex:
In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialise mutexes that are statically allocated. The effect is equivalent to dynamic initialisation by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.
And for default mutexes, attempting to lock a mutex that has been locked by the calling thread leads to undefined behaviour:
If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behaviour.
Upvotes: 2