Simple callback control using boost :: asio and C ++ 11 lambda

I am implementing a simple server with boost::asio

and thinking about the io-service-per-cpu model (each io_service has one thread).

What I want to do is let the io_service request some jobs for a different io_service (something like passing messages).

I think it boost::asio::io_service::post

can help me.

There are two io_service

s, ios1

, ios2

,

and task (function) bool func(arg *)

,

and a completion handler void callback(bool)

.

So I want it to ios1

request the job, ios2

start it and notify it ios1

when finished, and finally ios2

start the handler.

ios2.post( 
 [&ios1, arg_ptr, callback, func]
 {
    bool result = func(arg_ptr);
    ios1.post( []{ callback(result) } );
 } );

      

Does this code work? and is there a smarter and easier way?

EDIT:

I found that the second lamp inside ios1.post()

cannot reach the function pointer callback

. This is out of scope ... so I am trying a different way using boost::bind()

.

ios2.post(
 [&ios1, arg_ptr, callback, func]
 {
    ios1.post(  boost::bind( callback, func(arg_ptr) )  );
 } );

      

I removed one variable stack bool and it seems better.

But using C ++ 11 lambda and boost::bind

together doesn't look so cool.

How can I do this without boost::bind

?

+3


source to share


2 answers


I found that the second lamda inside ios1.post () cannot reach the function pointer callback. It goes beyond

I don't think that's the problem.

You are trying to capture callback

, but it is not a function pointer, it is a function. You don't need to capture the function, you can just call it! The same applies to func

, don't write it down, just call it. Finally, your internal lambda refers to result

without capturing it.

It will work if you fix these problems:



ios2.post(
        [&ios1, arg_ptr]
        {
            bool result = func(arg_ptr);
            ios1.post( [result]{ callback(result); } );
        }
    );

      

You second version is not exactly the same, because it func(arg_ptr)

will run on the ios1

not thread ios2

, and I'm not sure if any version is appropriate for your description:

So I want it to ios1

request the job, ios2

start it and notify it ios1

when finished, and finally ios2

start the handler.

Both code samples ios1

execute the handler callback

.

+2


source


#include <boost/asio/io_service.hpp>
#include <boost/function.hpp>
typedef int arg;
int main()
{
    arg * arg_ptr;
    boost::function<void(bool)> callback;
    boost::function<bool(arg *)> func;
    boost::asio::io_service ios1, ios2;
    ios2.post( 
     [&ios1, arg_ptr, callback, func]
     {
            bool result = func(arg_ptr);
            auto callback1 = callback;
            ios1.post( [=]{ callback1(result); } );
     } );
}

      



+1


source







All Articles