0

I have the following code:

pthread_mutex lock_row[M], lock_culm[M];
FUNCTION SIGNATURE (..., int i, int j, ...) {
   pthread_mutex_lock(&lock_row[i]);
   pthread_mutex_lock(&lock_culm[j]);
   ...CRITICAL CODE...
   pthread_mute_unlock(&lock_row[j]);
   pthread_mute_unlock(&lock_row[i]);
}

Can I get a deadlock between the first lock to the second? Let's say if we have a context switch after the first row, and other thread tries to lock something again? I don't really get this I would like to understand this a little further.

BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

1

Besides the probable typo when you try to unlock sth twice, this example will never deadlock. Context switches between the two lock-calls pose no threat to the mechanism involved here. Think of it as a getting a higher level of allowance. With each lock gained, this process or thread is allowed to do more. Each locking is a gate which might hold the process up until no other lock-holder prevents the entering of the higher level. Whatever happens between the two lockings does not matter as long as it does not change that level of allowance.

Alfe
  • 56,346
  • 20
  • 107
  • 159
0
   pthread_mutex_lock(&lock_row[i]);
   pthread_mutex_lock(&lock_culm[j]);

This is fine as long as all of your code takes these locks in this order - the lock_row lock first, then the lock_culm lock second. If another part of the code takes these same locks in the opposite order, then it can deadlock.

For this reason it is usual in complex programs to define the locking order - a global ordering of all the locks in the program, defining the order in which they should be taken.

caf
  • 233,326
  • 40
  • 323
  • 462