首页 > 解决方案 > 如何使用 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();
    }

//...

所以我的函数应该在与 io_service 相同的线程下执行。

PS:: 这是类的一部分,适用于客户端

标签: c++multithreadingboost-asio

解决方案


您可以在某处运行一个函数(可能作为post()相同的 -ed 任务io_service)。然后,完成后,只需开始下一个异步操作:

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);
}

推荐阅读