现在的位置: 首页 > 综合 > 正文

A thread pool for executing arbitrary tasks

2013年04月08日 ⁄ 综合 ⁄ 共 711字 ⁄ 字号 评论关闭

http://www.think-async.com/Asio/Recipes?skin=clean.nat%2casio%2cpattern#A_thread_pool_for_executing_arbi 

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();

抱歉!评论已关闭.