以下代码导致我的应用程序卡住,即使该程序只有一个线程在运行。
semaphore
是 boost::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.
关于c++ - 将写锁降级为读锁时 TMultiReadExclusiveWriteSynchronizer 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770664/