c++ - 将写锁降级为读锁时 TMultiReadExclusiveWriteSynchronizer 的行为

标签 c++ multithreading c++builder

以下代码导致我的应用程序卡住,即使该程序只有一个线程在运行。

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.

关于c++ - 将写锁降级为读锁时 TMultiReadExclusiveWriteSynchronizer 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770664/

相关文章:

c++ - 在 map 列表中添加新条目?

c++ - 安全方便的泛型散列(用于 STL 无序集和映射)成语?

c++ - 优化 Linux 套接字

python - 检查父线程是否正在运行

c++ - 在哈希表中搜索帮助!

c++ - 即使没有明确定义为内联,一个非常短的函数也可以内联吗?

java - 如果线程 B 希望看到线程 A 所做的更改,是否只能将最后的更改更改为 volatile 变量而不是全部?

delphi - CBuilder/Delphi 的 HTML 编辑器

c++ - 为什么我使用 istream::get(char*, streamsize n, char delim) 会得到奇怪的结果?

delphi - 你能帮忙把这个非常小的 C++ 组件翻译成 Delphi 吗?