如何知道boost::asio::io_context是否准备好?

问题描述 投票:0回答:1

我正在编写一个 HTTP 服务器。我写了以下内容并且效果很好:

boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, ...);
acceptor.async_accept(...);
auto server_thread = std::jthread([] { io_context.run(); });
// How do I ensure the server is ready? (before calling sendHTTPRequests)
sendHTTPRequests();

我想立即开始发送 HTTP 请求。有没有办法确保服务器已经启动并运行?

c++ boost-asio
1个回答
0
投票

你总是可以等待。

代码草图(未经测试...):

struct Sync
{
   std::mutex mutex;
   std:condition_variable condition;
   bool ready=false;
};
auto sync=std::make_shared<Sync>();

io_context.post([sync]() {
   {
      std::lock_guard<decltype(sync->mutex)> lock(sync->mutex);
      sync->ready=true;
   }
   sync->condition.notify_all();
});

auto server_thread = std::jthread([] { io_context.run(); });

std::unique_lock<decltype(sync->mutex)> lock(sync->mutex);
sync->condition.wait([sync]() { return sync->ready; } );
© www.soinside.com 2019 - 2024. All rights reserved.