如何在C++中使用boost创建线程池,如何将任务分配给线程池?

最佳答案

这个过程非常简单。首先创建一个asio::io_service和一个thread_group。用链接到io_service的线程填充thread_group。使用boost::bind函数将任务分配给线程。

要停止线程(通常是在退出程序时),只需停止io_service并加入所有线程即可。

您只需要这些标题:

#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>

这是一个例子:
/*
 * Create an asio::io_service and a thread_group (through pool in essence)
 */
boost::asio::io_service ioService;
boost::thread_group threadpool;


/*
 * This will start the ioService processing loop. All tasks
 * assigned with ioService.post() will start executing.
 */
boost::asio::io_service::work work(ioService);

/*
 * This will add 2 threads to the thread pool. (You could just put it in a for loop)
 */
threadpool.create_thread(
    boost::bind(&boost::asio::io_service::run, &ioService)
);
threadpool.create_thread(
    boost::bind(&boost::asio::io_service::run, &ioService)
);

/*
 * This will assign tasks to the thread pool.
 * More about boost::bind: "http://www.boost.org/doc/libs/1_54_0/libs/bind/bind.html#with_functions"
 */
ioService.post(boost::bind(myTask, "Hello World!"));
ioService.post(boost::bind(clearCache, "./cache"));
ioService.post(boost::bind(getSocialUpdates, "twitter,gmail,facebook,tumblr,reddit"));

/*
 * This will stop the ioService processing loop. Any tasks
 * you add behind this point will not execute.
*/
ioService.stop();

/*
 * Will wait till all the threads in the thread pool are finished with
 * their assigned tasks and 'join' them. Just assume the threads inside
 * the threadpool will be destroyed by this method.
 */
threadpool.join_all();

资料来源:Recipes < Asio

关于c++ - 如何在C++中使用boost创建线程池?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19500404/

10-11 22:40
查看更多