tmultireadexexclusivewritesynchronizer将写锁降级为读锁时的行为

Behaviour of TMultiReadExclusiveWriteSynchronizer when demoting write-lock to read-lock

本文关键字:读锁 tmultireadexexclusivewritesynchronizer 写锁 降级      更新时间:2023-10-16

下面的代码导致我的应用程序冻结,即使程序只有一个线程在运行。

semaphoreboost::shared_ptr<TMultiReadExclusiveWriteSynchronizer>

if (semaphore)
{
  semaphore->BeginWrite();
  // Perform write operations on the shared object here.
  semaphore->BeginRead();
  semaphore->EndWrite();
  // Perform read-only operations on the object, allowing other threads to also read.
  semaphore->EndRead();
  semaphore->BeginWrite(); // Program locks up here.
}

调试信息,用于@v。ouddou置评。

当我遍历代码时,只有一个线程。顺便说一下,这是一个窗口应用程序,所以程序入口点是WinMain(如果有关系的话)。

当我进入死亡行(最后一个semaphore->BeginWrite())时,程序冻结,如果我停止它,则有两个线程。我的主线程是在组装土地,但调用堆栈是WaitForSingleObject -> WaitForSingleObjectEx -> ZwWaitForSingleObject

还有一个没有堆栈信息的第二个线程,在RtlUserThreadStart的入口点。我认为这个线程只是为了我能够暂停应用程序的缘故。此时,在我的代码中创建第二个线程没有任何意义。

这似乎已经解决了问题。但是,它需要添加一个临界区来防止读过程中的死锁。

// Care: Two threads attempting to acquire the locks here would deadlock.
critical_section->Acquire();
semaphore->BeginRead();
semaphore->BeginWrite();
critical_section->Leave();
// Perform write operations on the shared object here.
semaphore->EndWrite();
// Perform read-only operations on the object, allowing other threads to also read.
semaphore->EndRead();
semaphore->BeginWrite(); // No longer deadlocks.