Sunday, October 30, 2011

Task Pool with boost::asio

We can design a simple task pool with the boost::aiso recipe, A thread pool for executing arbitrary tasks.

However, if you want to implement parallel computation, tbb:task_group is faster, or you should choose OpenMP. tbb:task_group schedules the execution of tasks, so the execution order is not guaranteed.

class TaskPool
{
public:
  TaskPool(size_t nthreads=1)
  {
    work_ = new boost::asio::io_service::work(service_);
    for (std::size_t i = 0; i < nthreads; ++i)
      threads_.create_thread(boost::bind(&boost::asio::io_service::run, &service_));
  }

  ~TaskPool()
  {
    if (work_)
      stop();
  }

  void stop(bool wait=true)
  {
    if (wait) {
      delete work_; // if not delete this, io_service::run will never exit
      threads_.join_all();
      service_.stop();
    } else {
      service_.stop();
      threads_.join_all();
      delete work_;
    }   
    work_ = NULL;
  }

  template <typename T>
  void run(T func)
  {
    service_.post(func);
  }

protected:
  boost::thread_group threads_;
  boost::asio::io_service service_;
  boost::asio::io_service::work* work_;
};

No comments:

Post a Comment