Chinaunix首页 | 论坛 | 博客
  • 博客访问: 410394
  • 博文数量: 54
  • 博客积分: 1186
  • 博客等级: 少尉
  • 技术积分: 668
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 04:57
文章分类

全部博文(54)

文章存档

2013年(1)

2012年(6)

2011年(47)

我的朋友

分类: C/C++

2011-05-04 07:42:33

呵呵,今天要写一个性能测试的程序,由于之前用过boost的thread,所以就采用了boost的thread库

程序大概是根据指定的参数来生成多个线程来进行一个操作…本来满简单的..但是之前时候不知道boost有进程组的支持…所以只能自己动态的建立一 大堆 thread ..放到一个容器中..然后在遍历join下,然后再在结束前delete他们,很麻烦..不过最后还是实现了。不过就在完成之后,同事晓哲给我看了一下 他的程序..用到了boost的thread_group ,这才发现原来boost也有进程组的支持阿…晕….刚才试着写了一个简单的程序…呵呵,根据指定参数生成指定个数的子程序… 很简单阿..再也不用遍历一遍每一个join一下了..join_all就搞定了..

下面是代码,呵呵,很简单吧

#include
#include
#include

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

本文转自 http://rainx.cn/blog/archives/109
阅读(11141) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~