boost::threadpool线程池使用实例

前言:

  • 什么是多线程?比如在做一些下载的程序时,同时开启5个下载任务,对应的其实就是多线程。在一些多线程的程序中,响应请求的个数(即线程)的个数过多的话就会造成系统资源损耗过多而宕机,一般最多线程是有上限的,而且每次创建线程和销毁线程都会大量损耗资源和时间。所以解决办法之一就是使用线程池控制线程个数,复用创建过的线程。
  • 线程池可以减少创建和切换线程的额外开销,利用已经存在的线程多次循环执行多个任务从而提高系统的处理能力。
示例:
#include "stdafx.h"
#include <iostream>  
#include <boost/bind.hpp>  
#include <boost/threadpool.hpp>  
using namespace std;  
using namespace boost::threadpool;

void first_task()  
{  
	for (int i = 0; i < 30; ++i)  
		cout << "first" << i << endl;  
}  
void second_task()  
{  
	for (int i = 0; i < 30; ++i)  
		cout << "second" << i << endl;  
}  
void third_task()  
{  
	for (int i = 0; i < 30; ++i)  
		cout << "third" << i << endl;  
}  
void task_with_parameter(int value, string str)  
{  
	printf("task_with_parameter with int=(%d).\n" ,value);  
	printf("task_with_parameter with string=(%s).\n" ,str.c_str());  
}  
void execute_with_threadpool()  
{  
	// 创建一个线程池,初始化为2个线程  
	pool tp(2);  

	// 调用4个线程函数  
	tp.schedule(&first_task); // 不带参数的执行函数  
	tp.wait(); <span style="white-space:pre">	</span>//等待前面的线程函数执行结束才继续执行后面的线程
	tp.schedule(&second_task);   
	tp.wait();
	tp.schedule(&third_task);   
	tp.schedule(boost::bind(task_with_parameter, 8, "hello")); // 带两个参数的执行函数  
	tp.schedule(&third_task);
	// 这儿函数会等到4个线程全部执行结束才会退出  
	while(1)
	{
		;
	}
}  

int _tmain(int argc, _TCHAR* argv[])
{
	execute_with_threadpool();  
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值