简体   繁体   English

C ++对象终止通知

[英]C++ object termination notification

In a C++ program, I have two reference counted objects: King and Heir . 在C ++程序中,我有两个引用计数对象: KingHeir 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. King是一个引用计数对象,当它的引用计数变为零时将被销毁。 If Heir holds a reference to King, then King's reference count will never go to zero. 如果继承人持有对King的引用,则King的引用计数将永远不会为零。 How can have Heir block until King is destroyed? 在King被摧毁之前,怎么能阻止继承人?

You can use a non-owning (or "weak") reference, similar to how weak_ptr works . 您可以使用非拥有(或“弱”)引用,类似于weak_ptr工作方式

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. 如果你需要有多个继承人等待并且对继承人有一些排序,你可以有一个“继承人选择器”对象来跟踪继承人列表及其优先顺序,当国王释放互斥锁时它将分配该互斥锁的所有权为列表中的下一个继承人。

Thanks @James. 谢谢@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. 最后,我让Heir在堆栈上创建一个计数为零的信号量,将指针传递给信号量给King,释放King,然后尝试获取信号量。 The count is zero, so Heir immediately blocks. 计数为零,所以继承人立即阻止。 When King's destructor is called, it calls 'release' on the semaphore. 当调用King的析构函数时,它会调用信号量上的“释放”。 This seems to work ok with the Rogue Wave semaphore. 这似乎适用于Rogue Wave信号量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM