C ++ Object Termination Notice

In a C ++ program, I have two counted objects: King and Heir . The heir needs to be blocked until King is destroyed. The king is a reference counted object that will be destroyed when the reference count is zero. If Heir has a reference to the king, then the king’s reference count will never be zero. How can Heir block until the King is destroyed?

+6
c ++ reference blocking
source share
2 answers

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

While waiting for the king to die, you can use the mutex that the king can hold until he dies, and the heir block waits for the king to free him.

If you need several heirs to wait, and someone has an order, you can have an heir object that keeps track of the list of heirs and their order of priority, and when the king releases the mutex he assigns ownership of this mutex to the next heir in the list.

+10
source share

Thanks @James. Here is the solution I ended up with:

The mutex method seemed promising, but most mutexes expect the resulting thread and thread release to be the same. In the end, I had a Semaphore Creator with a zero on the stack, pass the pointer to the semaphore to the king, release King, and then try to acquire the semaphore. The score is zero, so the Heir immediately blocks. When the destructor of the king is called, it calls "release" on the semaphore. This is similar to working with the Rogue Wave semaphore.

0
source share

All Articles