据我所知,升级锁试图解决经典的死锁示例,其中两个并发线程持有Read lock并尝试获取writelock将会死锁。
线程A:S锁定(获得)
线程B:S锁定(获得)
线程A:X锁(等待B释放S锁)
线程B:X锁定(等待A释放S锁定)DEADLOCKED
为什么同样的问题不是升级锁? This文档说只有一个线程可以被授予升级锁,并且允许这样做,而其他线程仍然保持S锁。有人可以解释为什么运行此模式的两个并发线程不会遇到死锁吗?
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
}
答案 0 :(得分:0)
有趣的是,我刚刚回答了SQL Server和UPDATE
语句的相同问题:How do UPDATE locks prevent a common form of deadlock?
答案的关键方面是可升级交易永远不会采取S锁定。他们马上U锁。因此,S锁和X锁之间永远不会发生冲突。
在您的示例中,
lock.AcquireSharedLock()
永远不应该存在。您 S-lock 或 U-lock。不是顺序,而是其中任何一个。