boost線程組

來源:互聯網
上載者:User

原文地址: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退出

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.