Boost logo

Boost Users :

Subject: Re: [Boost-users] How to design proper release of a boost::asio socket or wrapper thereof
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2017-04-06 03:02:54


On 6/04/2017 10:14, Christopher Pisz via Boost-users wrote:
> What if the server wants to send "Hello" to all clients every 5 minutes?
> You need a collection. If you have a collection, then you maintain a
> reference count when using shared_ptrs, and just killed the tutorials
> lifetime management scheme. In the end, you need to know when it is safe to
> remove the connection from a collection and destroy it.

Make a collection of weak_ptrs. When you go through and try to send to
them, some of them will have expired, and you can remove them from the
collection then. The rest are still alive (although some might error
out when you try to send to them, due to the way TCP works; if that
happens you can just close() them and they'll be expired the next time
you check).

If you want to explicitly disconnect a given connection, you simply need
to call shutdown() and close() on it (via a method on your connection
class), which will abort the pending receive and release the internal
references, so once you discard the local shared_ptr you just used to
close it then the connection object will be destroyed automatically.

(Note that it's not safe to assume you can destroy the object
immediately after calling close() on the socket -- if the receive was
still pending, it still needs to call the completion handler with the
error, which might happen later on a different thread. This is why
using shared_ptr is the preferred solution as it handles different
lifetime ordering correctly without explicit locking.)


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