您的位置:首页 > 其它

使用boost中的线程池

2015-05-11 11:15 155 查看
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace boost;
using namespace std;

void runChild(const int n)
{
cout << "我是第" << n << "个子线程" << endl;
sleep(1);
cout << "进程" << n << "退出" << endl;
}

int main(int argc, char** argv)
{
int num;
thread_group threads;

if (argc < 2)
{
cout << "请提供一个要生成线程数的参数" << endl;
exit(-1);
}

num = atoi(argv[1]);

cout << "我是主程序,我准备产生" << num << "个子线程" << endl;
for(int i = 0; i < num; i++)
{
threads.create_thread(bind(&runChild, i));
}
cout << "我是主程序,我在等子线程运行结束" << endl;
threads.join_all();
return 0;
}

编译&测试(我在我的ubuntu下测试的)

> g++ threadgroup.cc -lboost_thread
> ./a.out 3
如果在freebsd4下编译的话,如果使用pthread作为线程实现的话,需要明确指出pthread使用线程库,而且默认的template深度好像不能满足boost的需求..需要在编译时加上:

-ftemplate-depth-20 -boost
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: