#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
void task_1(int num)
{
for (int i = 0; i < 5; i ++)
std::cout << "task_1 " << i << std::endl;
}
void task_2(int num)
{
for (int i = 0; i < 5; i ++)
std::cout << "task_2 " << i << std::endl;
}
int main()
{
/*
* 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 io_service processing loop. All tasks
* assigned with io_service.post() will start executing.
*/
boost::asio::io_service::work* work;
/*
* This will add 2 threads to the thread pool. (You could just put it in a for loop)
*/
int thread_count = 2;
for (int i = 0; i < thread_count; ++ i)
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(task_1, 111));
ioService.post(boost::bind(task_2, 222));
/*
* This will stop the ioService processing loop. Any tasks
* you add behind this point will not execute.
*/
sleep(1);
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();
return 0;
}
boost::threadpool简单实例
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...