【问题标题】:How to run function asynchronous using boost::asio io_service如何使用 boost::asio io_service 异步运行函数
【发布时间】:2018-11-26 16:16:52
【问题描述】:

我有异步 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:: 这是类的一部分,适用于客户端

【问题讨论】:

    标签: c++ multithreading boost-asio


    【解决方案1】:

    您可以在某处运行一个函数(可能作为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);
    }
    

    【讨论】:

    • 非常感谢,我不知道 io_service::post(),但是如果我要使用 post(),我应该注意 io_service::work 吗?也许我应该这样做: boost::shared_ptr<:work> work_ = new io_context::work(service);而不是将 work_ 作为 func() 的参数?
    • 只要您在发布的函数中完成工作,从技术上讲,您不需要工作实例。这是一个不同的问题。 stackoverflow.com/questions/17156541/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    相关资源
    最近更新 更多