1. 程式人生 > >boost::threadpool執行緒池使用例項

boost::threadpool執行緒池使用例項

#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;
}