C++对象终止通知

发布于 2024-09-11 13:46:20 字数 181 浏览 6 评论 0原文

在 C++ 程序中,我有两个引用计数对象:KingHeir。继承人需要阻止,直到国王被摧毁。 King 是一个引用计数对象,当它的引用计数为零时,它将被销毁。如果 Heir 持有对 King 的引用,那么 King 的引用计数将永远不会为零。继承人怎么能阻止直到国王被摧毁?

In a C++ program, I have two reference counted objects: King and Heir. Heir needs to block until King is destroyed. King is a reference counted object which will be destroyed when it's reference count goes to zero. If Heir holds a reference to King, then King's reference count will never go to zero. How can have Heir block until King is destroyed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぽ尐不点ル 2024-09-18 13:46:20

您可以使用非拥有(或“弱”)引用,类似于 weak_ptr 如何工作

至于等到国王死了,你可以使用国王可以持有直到他死的互斥体,并让继承人块等待国王释放它。

如果您需要有多个继承人等待并且对继承人有一些顺序,您可以有一个“继承人选择器”对象来跟踪继承人列表及其优先顺序,当国王释放互斥体时,它将分配该互斥锁的所有权归列表中的下一个继承人所有。

You can use a non-owning (or "weak") reference, similar to how weak_ptr works.

As for waiting until the king is dead, you can use a mutex that the king can hold until he dies and have the heir block waiting for the king to release it.

If you need to have multiple heirs waiting and there is some ordering to the heirs, you can have an "heir selector" object that keeps track of the list of heirs and their order of precedence, and when the king releases the mutex it will assign ownership of that mutex to the next heir in the list.

离线来电— 2024-09-18 13:46:20

谢谢@詹姆斯。这是我最终采用的解决方案:

互斥体方法似乎很有前途,但大多数互斥体期望获取线程和释放线程相同。最后,我让 Heir 创建了一个堆栈上计数为零的信号量,将指向该信号量的指针传递给 King,释放 King,然后尝试获取该信号量。计数为零,因此 Heir 立即阻塞。当 King 的析构函数被调用时,它会调用信号量的“释放”。这似乎与 Rogue Wave 信号量一起工作正常。

Thanks @James. Here's the solution I ended up going with:

The mutex method seemed promising, but most mutexes expect the acquiring thread and releasing thread to be the same. In the end, I had Heir create a semaphore with a count of zero on the stack, pass a pointer to the semaphore to King, release King, and then attempt to acquire the semaphore. The count is zero, so Heir immediately blocks. When King's destructor is called, it calls 'release' on the semaphore. This seems to work ok with the Rogue Wave semaphore.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文