Is it possible to use Boost's asio to do non-blocking IO without using async callbacks? Ie 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?
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;
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.