C++对象终止通知
在 C++ 程序中,我有两个引用计数对象:King 和 Heir。继承人需要阻止,直到国王被摧毁。 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用非拥有(或“弱”)引用,类似于 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.
谢谢@詹姆斯。这是我最终采用的解决方案:
互斥体方法似乎很有前途,但大多数互斥体期望获取线程和释放线程相同。最后,我让 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.