0

Question

Assume that you have two mutexes, guard_mtx_1 and guard_mtx_2, that guards the access to the global lists, list_1 and list_2 in two threads that both run the following code snippet:

...
lock(guard_mtx_1);
Add(list_1, var_1);
Lock(guard_mtx_2);
Add(list_2, var_2);
Unlock(guard_mtx_1);
Unlock(guard_mtx_2);
...

Could a deadlock occur? If so, how could it be avoided?

My incomplete answer:

I don't see where the deadlock could occur. First thread locks out other thread lock at line:

lock(guard_mtx_1)

Then at line:

Unlock(guard_mtx_1)

Thread 2 can get to second line:

Add(list_1, var_1)

Thread 1 can unlock mutex at last line and the Thread 2 can now also get to the last line and do the same things as thread 1.

Or I'm missing something here?

Sigrid
  • 73
  • 7

1 Answers1

1

You miss nothing. Unless some other code path an lock guard_mtx_2 before locking guard_mtx_1 there is no deadlock. The out-of-natural-order unlock is harmless (and occasionally we must do this).

Deadlocks occur when two code paths can lock the mutexes (sp? should it be mutices? my spellchecker doesn't like either) in opposing order; that is there is no number to which you could assign each mutex that all threads lock the mutexes in increasing numerical order.

Joshua
  • 40,822
  • 8
  • 72
  • 132