Recipes

A thread pool for executing arbitrary tasks

Create an io_service:

  asio::io_service io_service;

and some work to stop its run() function from exiting if it has nothing else to do:

  asio::io_service::work work(io_service);

Start some worker threads:

  boost::thread_group threads;
  for (std::size_t i = 0; i < my_thread_count; ++i)
    threads.create_thread(boost::bind(&asio::io_service::run, &io_service));

Post the tasks to the io_service so they can be performed by the worker threads:

  io_service.post(boost::bind(an_expensive_calculation, 42));
  io_service.post(boost::bind(a_long_running_task, 123));

Finally, before the program exits shut down the io_service and wait for all threads to exit:

  io_service.stop();
  threads.join_all();
Topic revision: r2 - 28 Jul 2008 - 11:58:47 - ChrisKohlhoff
 
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback