原文地址:http://rainx.cn/blog/archives/109
呵呵,今天要寫一個效能測試的程式,由於之前用過boost的thread,所以就採用了boost的thread庫
程式大概是根據指定的參數來產生多個線程來進行一個操作…本來滿簡單的..但是之前時候不知道boost有進程組的支援…所以只能自己動態建立一大堆 thread ..放到一個容器中..然後在遍曆join下,然後再在結束前delete他們,很麻煩..不過最後還是實現了。不過就在完成之後,同事曉哲給我看了一下他的程式..用到了boost的thread_group ,這才發現原來boost也有進程組的支援阿…暈….剛才試著寫了一個簡單的程式…呵呵,根據指定參數產生指定個數的子程式… 很簡單阿..再也不用遍曆一遍每一個join一下了..join_all就搞定了..
下面是代碼,呵呵,很簡單吧
#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++ -g -Wall -O0 test.cc -o boost -lboost_thread
> ./boost 3
sudo apt-get install libboost-thread1.40-dev boost線程庫需要額外安裝
*****output******
我是主程式,我準備產生3個子線程
我是第0個子線程
我是第1個子線程
我是主程式,我在等子線程運行結束
我是第2個子線程
進程進程10退出退出
進程2退出
完