asio C++ library Home | Download | Documentation | Source | Mailing List | Blog

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.post(boost::bind(an_expensive_calculation, 42));
io_service.stop();
threads.join_all();
Home | Download | Documentation | Source | Mailing List | Blog