Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] wrap lambda async_receive call
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-03-17 22:53:44


On 18/03/2015 14:23, Andrew Hundt wrote:
> In C++11 is there an easy way to use
> boost::asio::io_service::strand::wrap() on a lambda function handling
> the return of an async_receive call?
>
> As noted in the docs (link below it looks like there has to be an
> implementation of asio_handler_invoke but I'm not sure how that would
> work for a lambda function. Looking through the C++11 examples I can't
> find any examples of using a strand. Any help would be greatly appreciated.
>
> http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/overview/core/strands.html

You only need to define asio_handler_invoke if something more
complicated than simply trying the call operator is required to invoke
your handler object type.

strand::wrap defines asio_handler_invoke for you such that intermediate
handlers still route through the strand. So all you should need to do is:

   async_read(mysocket, buffers, mystrand.wrap([=](const error_code& ec,
size_t count)
   {
     // ...
   }));

(It's important to copy captured variables, as by the time the handler
is called the original function will have exited.)

Having said this, using lambdas can get tricky in real-world code, as
it's common to want to start the same read operation when the first
completes, and so on. Unless you're very careful this can quickly get
messy. Using coroutines can sometimes help with this, if you're
familiar with them already.


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