我有一个使用 Boost.Asio 进行 TCP 和 UDP 套接字通信的应用程序。我知道“Asio”中的“A”代表异步,因此该库致力于鼓励您尽可能使用异步 I/O。我有一些情况,同步套接字读取更可取。但与此同时,我想为所述接收调用设置超时,因此不可能无限期地阻塞读取。
这似乎是 Boost.Asio 用户中非常常见的问题,过去 Stack Overflow 曾就该主题提出过以下问题:
- C++ Boost ASIO:如何超时读/写?
- asio::读取超时
- 提高asio超时
- 如何在 boost asio 中设置阻塞套接字的超时?
甚至可能还有更多。甚至还有文档中的示例了解如何实现带超时的同步操作。它们归结为将同步操作转换为异步操作,然后与异步操作并行启动它asio::deadline_timer
。如果超时到期,计时器的到期处理程序可以取消异步读取。这看起来像这样(摘自上面链接示例的片段):
std::size_t receive(const boost::asio::mutable_buffer& buffer,
boost::posix_time::time_duration timeout, boost::system::error_code& ec)
{
// Set a deadline for the asynchronous operation.
deadline_.expires_from_now(timeout);
// Set up the variables that receive the result of the asynchronous
// operation. The error code is set to would_block to signal that the
// operation is incomplete. Asio guarantees that its asynchronous
// operations will never fail with would_block, so any other value in
// ec indicates completion.
ec = boost::asio::error::would_block;
std::size_t length = 0;
// Start the asynchronous operation itself. The handle_receive function
// used as a callback will update the ec and length variables.
socket_.async_receive(boost::asio::buffer(buffer),
boost::bind(&client::handle_receive, _1, _2, &ec, &length));
// Block until the asynchronous operation has completed.
do io_service_.run_one(); while (ec == boost::asio::error::would_block);
return length;
}
这实际上是一个相对干净的解决方案:启动异步操作,然后手动轮询asio::io_service
一次执行一个异步处理程序,直到async_receive()
完成或计时器到期。
然而,如果套接字的底层 I/O 服务已经在一个或多个后台线程中运行,情况会怎样呢?在这种情况下,无法保证异步操作的处理程序将由上面代码片段中的前台线程运行,因此run_one()
直到稍后某个可能不相关的处理程序执行后才会返回。这将使套接字读取相当无响应。
asio::io_service
has a poll_one()
函数将在不阻塞的情况下检查服务的队列,但我没有找到阻止前台线程(模拟同步调用行为)直到处理程序执行的好方法,除了没有正在执行的后台线程的情况之外asio::io_service::run()
已经。
我看到了两种可能的解决方案,但我都不喜欢:
使用条件变量或类似的构造使前台线程在启动异步操作后阻塞。在处理程序中async_receive()
调用,向条件变量发出信号以解除线程阻塞。这会导致每次读取时出现一些锁定,我希望避免这种情况,因为我希望在 UDP 套接字读取上实现最大可能的吞吐量。否则,它是可行的,并且可能是我会做的,除非出现更好的方法。
确保套接字有自己的asio::io_service
没有由任何后台线程运行。这使得在需要的情况下使用套接字的异步 I/O 变得更加困难。
有什么其他方法可以安全地实现这一目标吗?
Aside:对于之前的 SO 问题,有一些答案提倡使用SO_RCVTIMEO
套接字选项来实现套接字读取超时。这在理论上听起来很棒,但它似乎至少在我的平台上不起作用(Ubuntu 12.04,Boost v1.55)。我可以设置套接字超时,但它不会给 Asio 带来预期的效果。相关代码在/boost/asio/detail/impl/socket_ops.ipp
:
size_t sync_recvfrom(socket_type s, state_type state, buf* bufs,
size_t count, int flags, socket_addr_type* addr,
std::size_t* addrlen, boost::system::error_code& ec)
{
if (s == invalid_socket)
{
ec = boost::asio::error::bad_descriptor;
return 0;
}
// Read some data.
for (;;)
{
// Try to complete the operation without blocking.
signed_size_type bytes = socket_ops::recvfrom(
s, bufs, count, flags, addr, addrlen, ec);
// Check if operation succeeded.
if (bytes >= 0)
return bytes;
// Operation failed.
if ((state & user_set_non_blocking)
|| (ec != boost::asio::error::would_block
&& ec != boost::asio::error::try_again))
return 0;
// Wait for socket to become ready.
if (socket_ops::poll_read(s, 0, ec) < 0)
return 0;
}
}
如果套接字读取超时,则调用recvfrom()
上面会返回EAGAIN
or EWOULDBLOCK
,它被翻译成boost::asio::error::try_again
or boost::asio::error::would_block
。在这种情况下,上面的代码将调用poll_read()
函数,对于我的平台来说是这样的:
int poll_read(socket_type s, state_type state, boost::system::error_code& ec)
{
if (s == invalid_socket)
{
ec = boost::asio::error::bad_descriptor;
return socket_error_retval;
}
pollfd fds;
fds.fd = s;
fds.events = POLLIN;
fds.revents = 0;
int timeout = (state & user_set_non_blocking) ? 0 : -1;
clear_last_error();
int result = error_wrapper(::poll(&fds, 1, timeout), ec);
if (result == 0)
ec = (state & user_set_non_blocking)
? boost::asio::error::would_block : boost::system::error_code();
else if (result > 0)
ec = boost::system::error_code();
return result;
}
我剪掉了为其他平台有条件编译的代码。正如你所看到的,如果套接字不是非阻塞套接字,它最终会调用poll()
具有无限超时,因此会阻塞,直到套接字有数据要读取(并在超时时阻止尝试)。就这样SO_RCVTIMEO
选项无效。