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.