boost::io_service::post线程安全

Is boost::io_service::post thread safe?

本文关键字:线程 安全 post io boost service      更新时间:2023-10-16

从处理程序中发布新的处理程序是线程安全的吗?即,调用io_service::run()的线程是否可以将新的Handler发布到同一io_service?

感谢

根据文档,从io_service的单个实例的处理程序内发布处理程序是安全的。

线程安全性

不同对象:安全。

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

我认为这不是因为下面的代码没有返回3000000,并且我没有看到互斥体同步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;
}