Boost logo

Boost Users :

Subject: Re: [Boost-users] Mixing signals2 and asio mechanism failing
From: Scott Mueller (smueller_at_[hidden])
Date: 2013-10-21 14:37:11


On Saturday, October 19, 2013 2:47 PM, ustulation wrote:

>I've the following:
>
><1> a single instance of io_service object with a program life-time and several threads calling it's run() method. io_service::work is given to it so >that it never terminates (unless we stop it).
>
><2> class A which has boost::signals2::signal connecting functions for
>callback. * async operations (eg., async_read_until, async_write etc)
>
><3> class B which is derived from std::shared_from_this ; * has a
>composition of class A as std::unique_ptr which is instantiated in B's constructor ; <c> has functions/listeners which are registered with signals >of class A (eg., signals2::connection connectionObj =
>uniqPtrA->someSig.connect([=]{shared_from_this_ptrB->listenerFuncOfB();}
>uniqPtrA->);
>
><4> Another thread outside the thread-pool of <1> above which instantiates
>(and manages) class B:
>auto ptrB = std::make_shared(); //and further operations.
>
>The problem is when I need to destroy ptrB I can't. For instance, i call
>some method of class B on ptrB to clear all connections it has with class A
>and allow ptrB to go out of scope, but class B destructor is never called:
>
>{//local scope
>auto ptrB = std::make_shared();
>ptrB->connectListenersToA();
>/* eg auto self = shared_from_this(); connectionObj =
>uniqPtrA->someSig.connect([=]{self ->listenerFuncOfB();}); referring to <3>
>above */
>//... do some operations
>ptrB->disconnectListenersWithA(); //eg connectionObj.disconnect(); referring
>to <3> above
>}//Scope ends I want ptrB to destroy the underlying pointer.
>
>The ptrB destructor is never called because signals2::connection::disconnect
>does not seem to wipe out the given slot so the shared_ptr reference of B
>remains with the signal in class A as anonymous functor (due to lambda in
><3> above) containing it does not get destroyed.
>
>How do I achieve this?

Have you tried to use track_foreign so that boost uses the weak reference of your shared_ptr as an analogue for your connection object? You can even do this with std::shared_ptr, instead of boost::shared_ptr<>, since the traits specializations are in place (with a properly configured environment). Then your connect call looks like this:
//ptrB->connectListenersToA();
// would do something like this
uniqPtrA->someSig.connect(&B::listenerFuncOfB, this).track_foreign(shared_from_this());

If you do all of this, then you can just cut your shared_ptrs free and they'll get destroyed. Signals2 will store a weak_ptr instead, and get rid of that some time afterward.

Best regards,

M. Scott Mueller


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net