开发者

Is boost::io_service::post thread safe?

开发者 https://www.devze.com 2023-03-13 14:14 出处:网络
Is it thread safe to post new handlers from within a handler? I.e. Can threads that called the io_service::run() post new Handlers to the sam开发者_如何学Goe io_service?

Is it thread safe to post new handlers from within a handler? I.e. Can threads that called the io_service::run() post new Handlers to the sam开发者_如何学Goe io_service?

Thanks


It is safe to post handlers from within a handler for a single instance of an io_service according to the documentation.

Thread Safety

Distinct objects: Safe.

Shared objects: Safe, with the exception that calling reset() while there are unfinished run(), run_one(), poll() or poll_one() calls results in undefined behaviour.


I think it's not because the following code didn't return 3000000 and I didn't see mutex synching the internal queue of io_service neither a lock-free queue.

#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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消