Boost asio non-blocking IO without callbacks

蓝咒 提交于 2019-12-11 13:37:37

问题


Is it possible to use Boost's asio to do non-blocking IO without using async callbacks? I.e. equivalent to the O_NONBLOCK socket option.

I basically want this function:

template<typename SyncWriteStream,
         typename ConstBufferSequence>
std::size_t write_nonblock(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers);

This function will write as many bytes as it can and return immediately. It may write 0 bytes.

Is it possible?


回答1:


Yes, using the non_blocking() method to put the socket into Asio non-blocking mode:

template<typename SyncWriteStream,
         typename ConstBufferSequence>
std::size_t write_nonblock(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers)
{
    s.non_blocking(true);
    boost::system::error_code ec;
    auto bytes = s.send(buffers, 0, ec);
    if (bytes == 0 && !(ec == boost::asio::error::would_block))
        throw boost::system::system_error(ec, "write_nonblock send");
    return bytes;
}



回答2:


The way with s.non_blocking(true) would not work. If you check send implementation, it uses socket_ops::sync_send, which does poll_write if send failed.

So it is still blocking on top level.



来源:https://stackoverflow.com/questions/35150923/boost-asio-non-blocking-io-without-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!