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?
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.
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.