0

I have async tcp server, that read async massage from client. 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.

PS:: This is part of classs, that works with client

sehe
  • 374,641
  • 47
  • 450
  • 633
Childcity
  • 19
  • 7

1 Answers1

1

You can just run a function somewhere (possibly as a post()-ed task on the same io_service). 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:

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);
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Thanks a lot, I don't know about io_service::post(), but if I will use post(), should I take care about io_service::work ? Maybe I should do something like this: boost::shared_ptr work_ = new io_context::work(service); and than put work_ as parameter to func() ? – Childcity Jun 17 '18 at 19:51
  • As long as you do the work in the function posted, you don't technically need the work instance. That's a different question though. https://stackoverflow.com/questions/17156541/why-do-we-need-to-use-boostasioio-servicework – sehe Jun 17 '18 at 20:28