C++ 如何运行 2 boost :asio: io_context at the same time

标签 c++ boost

我有 2 个 boost::asio::io_context 变量,一个用于我的 Raspberry Pi 和我的 arduino 之间的连接,另一个用于 Raspberry Pi 和客户端之间通过 tcp 的连接服务器。 我已经分别测试了这两个连接,它们工作得很好。但是,当我尝试加入他们时,它不起作用。我知道通过制作两个 io.run,第二个将永远不会进入,因为程序将卡在第一个中,那么我如何将 io.run 插入到 io_context.run() 中?

我的主要内容如下:

boost::asio::io_context io_context;
boost::asio::io_context io;
int main{
  //create a server object to accept incoming client connections
  tcp_server server(io_context);

  open_port_arduino();
  
  start = std::chrono::high_resolution_clock::now(); //time_init
  //writes to arduino with intervals of 2 seconds
  tim.expires_after(boost::asio::chrono::seconds {2});
  tim.async_wait(timer_handler);
  //reads from arduino
  start_read_arduino();

  io.run();
  io_context.run();
}

最佳答案

回复your comment : 你不需要第二个 io_context。

但是,您可以(另请参见 Do we need multiple io_service per thread for threaded boost::asio server with a single acceptorhttps://theboostcpplibraries.com/boost.asio-scalability)。

一个好处可能是线程隔离:如果您在单独的线程上运行单独的上下文,则存在隐式任务序列化。 (与多线程上的单个上下文对比,其中任务可能需要手动序列化,例如使用链)。

我想对您来说“修复”它的最直接的方法是简单地将一个 reference 传递给所有各方:

Live On Coliru

static io_context io;

struct tcp_server {
    tcp_server(io_context& ctx) : _ctx(ctx) {}
  private:
    io_context& _ctx; // REFERENCE
};

int main() {
    tcp_server server(io);

    // ...

(现场演示按预期打印“定时器回调:成功”)

多线程

如果您的某些 IO 任务阻塞了很长一段时间,您将需要运行多个线程。在那种情况下,我会切换将执行程序传递给您的类的方法,并确保它们将其包装成股:

boost::asio::thread_pool io(2); // two threads
using boost::asio::any_io_executor;

struct tcp_server {
    tcp_server(any_io_executor ex) : _ex(make_strand(ex)) {}
  private:
    any_io_executor _ex;
};

然后

int main() {
    //create a server object to accept incoming client connections
    tcp_server server(io.get_executor());

同样, Live demo 按预期打印“定时器回调:成功”。

关于C++ 如何运行 2 boost :asio: io_context at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65642000/

相关文章:

c++ - 来自 stdint.h 的快速类型的溢出行为

c++ - 在每个线程完成后停止 io_service

c++ - 获取基于另一个 vector 构建的 vector 成员的索引

c++ - 杀死魔数(Magic Number): "const int" vs "constexpr int" (or is there no difference in the end)

c++ - 多个开源库中的多个 zlib,链接器错误

c++ - 如何判断 bjam 正在使用哪些优化来构建 boost

python - 一起调试boost暴露的Python和C++

c++ - Boost::asio::async_read() 缓冲区损坏问题

c++ - 考虑多种情​​况,在 C++ 中解析英国用户的全名

c++ - 当跨构造函数边界抛出异常时,borland C++ 编译器不会撤消内存分配?