Boost logo

Boost Users :

Subject: [Boost-users] asio::io_service as a thread-pool executor
From: aiooua (aiooua_at_[hidden])
Date: 2011-09-08 18:50:07

I'm trying to use boost::asio::io_service as a thread pool executor.
Here's my attempt:

  using std::vector;
  using boost::bind;
  using boost::thread;
  using boost::shared_ptr;
  using boost::asio::io_service;
  class executor
    executor(size_t n): service_(n), work_(service_)
      for (size_t i = 0; i < n; i++)
        shared_ptr<thread> worker(new thread(bind(&io_service::run,
      for (auto i = pool_.begin(); i != pool_.end(); ++i)
    template<typename F> void submit(F task)
    io_service service_;
    io_service::work work_;
    vector<shared_ptr<thread> > pool_;
  void work() {}
  void other_work(const char *c) {}
  struct functor_work { void operator()() {} };
  auto lambda = [] {};
  int main()
    executor e(4);
    e.submit(boost::bind(other_work, "input"));
Is this usage correct or am I missing anything here? The bit I'm not
sure about in particular is this:
Is it guaranteed that the io_service::run will wait for the completion
of the posted jobs (via io_service::post) after I have called
io_service::stop? In other words, do I have to explicitly ensure that
my executor instance lives at least as long as the last submitted job
has finished? Or can I assume that io_service::run will only return
after all its posted jobs have had a chance to finish?

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at