2
votes

I understand that upgrade lock tries to solve classic deadlock example where two concurrent threads holding onto Read lock and trying to acquire writelock will deadlock.

Thread A: S lock (acquired)

Thread B: S lock (acquired)

Thread A: X lock (waiting for B to release S lock)

Thread B: X lock (waiting for A to release S lock) DEADLOCKED

Why same problem is not with upgrade lock? This documentation says that only one thread may be granted upgrade lock and it is permitted to do so while other threads are still holding onto S lock. Can someone explain why two concurrent threads running this pattern will not run into deadlock?

  lock.AcquireSharedLock()      // Thread A and B both acquired this S lock

  lock.EnterUpgradeableReadLock();  // Only one (e.g. A) acquired U lock and other (e.g. B) is blocked here.

  if(somecondition)
  {
    lock.AcquireExclusiveLock();   // A tries to acquire X lock. But wouldn't it get blocked since B is already holding onto S lock? B is already blocked, so this has to be a deadlock
  }
1

1 Answers

0
votes

It's funny that I have just answered the same question for SQL Server and UPDATE statements: How do UPDATE locks prevent a common form of deadlock?

The key aspect to the answer is that upgradable transactions never take an S-lock. They immediately U-lock. Therefore, there is never a conflict between an S-lock and an X-lock.

In your example,

lock.AcquireSharedLock()

should never exist. You either S-lock or U-lock. Not in sequence, but either of them.