简体   繁体   English

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

[英]How to run function asynchronous using boost::asio io_service

I have async tcp server, that read async massage from client. 我有一个异步TCP服务器,从客户端读取异步消息。 I should make some manipulation with massage that I rad and than send answer to client. 我应该对按摩进行一些操作,然后将答案发送给客户。 Manipulations should be asynchronous, and after manipulations will be done, server should send answer to client. 操作应该是异步的,并且在完成操作后,服务器应将答案发送给客户端。

I want to make next: 我想做下一个:

//...

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

//...

so my func should be executed under the same threads as io_service. 因此,我的func应该在与io_service相同的线程下执行。

PS:: This is part of classs, that works with client PS ::这是课程的一部分,可与客户一起使用

You can just run a function somewhere (possibly as a post() -ed task on the same io_service ). 您可以只在某个地方运行函数(可能是在同一io_service上作为post()任务)。 Then, when it's done, just start the next async operation: 然后,完成后,只需启动下一个异步操作即可:

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

However, in this case it might be simpler to just chain from inside the func : 但是,在这种情况下,仅从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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM