Some clarification needed about synchronous versus asynchronous asio operations

前端 未结 3 1014
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 22:54

As far as I know, the main difference between synchronous and asynchronous operations. I.e. write() or read() vs async_write() and

3条回答
  •  孤独总比滥情好
    2020-11-30 23:03

    synchronous is easy to control the program flow.

    asynchronous has better performance since it need not save/restore registers for fiber tasks.

    asynchronous uses callback and hard to programmer. We can try promise-cpp to make the asynchronous flow like synchronous --

    Example of http client --

    //<1> Resolve the host
    async_resolve(session->resolver_, host, port)
    
    .then([=](tcp::resolver::results_type &results) {
        //<2> Connect to the host
        return async_connect(session->socket_, results);
    
    }).then([=]() {
        //<3> Write the request
        return async_write(session->socket_, session->req_);
    
    }).then([=](std::size_t bytes_transferred) {
        boost::ignore_unused(bytes_transferred);
        //<4> Read the response
        return async_read(session->socket_, session->buffer_, session->res_);
    
    }).then([=](std::size_t bytes_transferred) {
        boost::ignore_unused(bytes_transferred);
        //<5> Write the message to standard out
        std::cout << session->res_ << std::endl;
    
    }).then([]() {
        //<6> success, return default error_code
        return boost::system::error_code();
    }, [](const boost::system::error_code err) {
        //<6> failed, return the error_code
        return err;
    
    }).then([=](boost::system::error_code &err) {
        //<7> Gracefully close the socket
        std::cout << "shutdown..." << std::endl;
        session->socket_.shutdown(tcp::socket::shutdown_both, err);
    });
    

    Full code here

提交回复
热议问题