如何使用 boost::asio io_service 运行 异步函数

How to run function asynchronous using boost::asio io_service

我有异步 tcp 服务器,它从客户端读取异步消息。我应该通过按摩进行一些操作,而不是将答案发送给客户。操作应该是异步的,操作完成后,服务器应该向客户端发送应答。

我想做下一个:

//...

    std::string answer;
    boost::asio::io_service &io_service_;

    void do_read(){
        //async read from client and call on_read()
    }

    void on_read(std::string msg){ 

        //here I have a problem - I don't know, how to call func() asynchronous
        //I want to do something like this:
        RunAcync(boost::bind(&CClientSession::func, shared_from_this(), msg)
                , boost::bind(&CClientSession::on_func_executed, shared_from_this())
                ,io_service_ ); 

        do_read();
    }

    void func(std::string msg) {
        //do long work hare with msg
        answer = msg;
    }

    void on_func_executed(){
        do_write(answer);
    }

    void do_write(std::string msg){
        //async write to client and call on_write()
    }

    void on_write(){
        do_read();
    }

//...

所以我的 func 应该在与 io_service.

相同的线程下执行

PS:: 这是类的一部分,与客户端一起工作

你可以在某处 运行 一个函数(可能是在同一个 io_service 上的 post() 编辑任务)。然后,完成后,开始下一个异步操作:

void on_read(std::string msg){ 
    auto self = shared_from_this();
    io_service_.post(
        boost::bind(&CClientSession::func, self, msg, boost::bind(&CClientSession::on_func_executed, self)));

    do_read();
}

void func(std::string msg, std::function<void()> on_complete) {
    //do long work hare with msg
    answer = msg;
    on_complete();
}

但是,在这种情况下,从 func:

内部链接可能更简单
void on_read(std::string msg){ 
    io_service_.post(
        boost::bind(&CClientSession::func, shared_from_this(), msg));

    do_read();
}

void func(std::string msg) {
    //do long work hare with msg
    answer = msg;
    do_write(answer);
}