【问题标题】:Is boost::io_service::post thread safe?boost::io_service::post 线程安全吗?
【发布时间】:2011-09-16 04:34:14
【问题描述】:

在处理程序中发布新的处理程序是线程安全的吗? IE。调用io_service::run() 的线程可以将新的处理程序发布到同一个io_service 吗?

谢谢

【问题讨论】:

    标签: c++ thread-safety boost-asio boost-thread


    【解决方案1】:

    根据文档,safe 在处理程序中为 io_service 的单个实例发布处理程序。

    线程安全

    不同的对象:安全。

    共享对象:安全,但在调用 reset() 时除外 还有未完成的run()、run_one()、 poll() 或 poll_one() 调用导致 未定义的行为。

    【讨论】:

      【解决方案2】:

      我认为这不是因为下面的代码没有返回 3000000 并且我没有看到 mutex 同步 io_service 的内部队列和无锁队列。

      #include <boost/asio/io_service.hpp>
      #include <boost/thread.hpp>
      #include <boost/thread/detail/thread_group.hpp>
      #include <memory>
      
      void postInc(boost::asio::io_service *service, std::atomic_int *counter) {
        for(int i = 0; i < 100000; i++) service->post([counter] { (*counter)++; });
      }
      
      int main(int argc, char **argv)
      {
        std::atomic_int counter(0);
      
        {
          boost::asio::io_service service;
          boost::asio::io_service::work working(service);
          boost::thread_group workers;
      
          for(size_t i = 0; i < 10;++i)     workers.create_thread(boost::bind(&boost::asio::io_service::run, &service));
      
          boost::thread_group producers;
          for (int it = 0; it < 30; it++)
          {
            producers.add_thread(new boost::thread(boost::bind(postInc,&service,&counter)));
          }
      
          producers.join_all();
          std::cout << "producers ended" << std::endl;
      
          service.stop();
          workers.join_all();
        }
      
        std::cout << counter.load();
      
        char c; std::cin >> c;
        return 0;
      }
      

      【讨论】:

      • 你不应该停止服务。它在workers 完成工作之前停止。
      • 你应该在加入工人时停止服务
      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2023-03-29
      • 1970-01-01
      • 2017-09-17
      • 2013-09-24
      • 2011-12-30
      • 1970-01-01
      • 2011-12-18
      相关资源
      最近更新 更多