views:

105

answers:

2

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?

+10  A: 

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.

James McNellis
Bah.. we answered the same thing and you added a little bit more on the waiting part. Deleted mine and upped yours. Just to add, the Heir should hold the weak_ptr reference to the King.
SB
+1 for using a mutex for notification
Luther Blissett
The weak_ptr won't work - at least not without polling. In order to execute a blocking method on King, you have to de-reference the weak-ptr. When this happens, you get a strong reference to the object and hold it until it's in scope.
brianegge
@brianegge: You need a mutex or some other signalling method to ensure there is only one king. The `weak_ptr` only gives you the ability for the heir to have a reference to the king but not prevent the king from dying.
James McNellis
@brianegge: Or, the king holds a strong pointer to the mutex which the heirs copy before they try to enter the mutex. The weak pointer is made weak again after the copy finished.
Luther Blissett
A: 

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.

brianegge