问题
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