John Humphreys - w00te John Humphreys - w00te - 2 months ago 19
C++ Question

Does order of unlocking mutexes make a difference here?

Let's say I have two variables,

protected_var1
and
protected_var2
. Let's further assume that these variables are updated via multiple threads, and are fairly independent in that usually one or the other but not both is worked on - so they both have their own mutex guard for efficiency.

Assuming:

-I always lock mutexes in order (mutex1 then mutex2) in my code in regions where both locks are required.

-Both mutexes are used many other places by them selves (like just lock mutex1, or just lock mutex2).

Does the order in which I unlock the mutexes at the end of a function using both make a difference in this situation?

void foo()
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);

int x = protected_var1 + protected_var2;

pthread_mutex_unlock(&mutex1); //Does the order of the next two lines matter?
pthread_mutex_unlock(&mutex2);
}


I was asked a question a long time ago in an interview regarding this situation, and I came out feeling that the answer was yes - the order of those two unlocks does matter. I cannot for the life of me figure out how a deadlock could result from this though if the locks are always obtained in the same order wherever both are used.

NPE NPE
Answer

I cannot for the life of me figure out how a deadlock could result from this though if the locks are always obtained in the same order wherever both are used.

In these circumstances, I don't think the order of unlocking the mutexes could be the cause of a deadlock.

Since pthread_mutex_unlock() doesn't block, both mutexes would always get unlocked regardless of the order of the two calls.

Note that if you attempt to acquire any locks between the two unlock calls, this can change the picture completely.