您的位置:首页 > 其它

简单使用Boost线程池threadpool

2016-03-29 16:43 447 查看
场景:

1.在一些多线程的程序中,比如服务端响应请求时,可以同时响应多个客户端的请求,但是响应请求的个数(即线程)的个数过多的话就会造成系统资源损耗过多而宕机,还比在做一些下载的程序时,可同时开5个下载任务,对应的其实就是线程。但是最多线程是有上限的,而且每次创建线程和销毁线程都会大量损耗资源和时间。所以解决办法之一就是使用线程池控制线程个数,复用创建过的线程。

threadpool直接使用Boost库,不需要另外编译Boost库

只是开启线程,调度线程的数量,不对单个线程进程操作(比如暂停,恢复,停止)
编译的时候注意加上链接库:
LIBS := -lboost_thread

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <boost/threadpool.hpp>

using namespace std;
using namespace boost::threadpool;

void task_1()
{
cout << "task_1 start" << endl;
cout << "thead_id(task_1): " << boost::this_thread::get_id() << endl;
for (int i = 0; i < 10; i++)
{
cout << "1111111111111111111111111" << endl;
sleep(1);
}
}

void task_2()
{
cout << "task_2 start" << endl;
cout << "thead_id(task_2): " << boost::this_thread::get_id() << endl;
for (int i = 0; i < 30; i++)
{
cout << "222222222222222222222222" << endl;
sleep(1);
}
}

void DoGetVersionNoForUpdate(int a)
{
cout << "task_3 start" << endl;
cout << "thead_id(task_3): " << boost::this_thread::get_id() << endl;
for (int i = 0; i < 5; i++)
{
cout << a*a << endl;
sleep(1);
}
}

int main(int argc, char *argv[])
{
//设置允许开启的线程数
pool tp(10);

//加入线程调度,可以通过指针传参
tp.schedule(&task_1);
tp.schedule(&task_2);
int i =10;
tp.schedule(boost::bind(DoGetVersionNoForUpdate, i));

//tp.wait();

return (0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: