利用C++ 11特性實現多執行緒計數器,多執行緒計數器

來源:互聯網
上載者:User

利用C++ 11特性實現多執行緒計數器,多執行緒計數器

許多並行計算程式,需要確定待計算資料的編號,或者說,多線程間通過編號而耦合。此時,通過利用C++ 11提供的atomic_?type類型,可實現多安全執行緒的計數器,從而,降低多線程間的耦合,以便於書寫多線程程式。

以計數器實現為例子,示範了多執行緒計數器的實現技術方法,代碼如下:

//目的: 測試利用C++ 11特性實現計數器的方法//作業系統:ubuntu 14.04//publish_date: 2015-1-31//注意所使用的編譯命令: g++ -Wl,--no-as-needed -std=c++0x counter.cpp -lpthread#include <iostream>#include <atomic>#include <thread>#include <vector>using namespace std;atomic_int Counter(0);int order[400];void work(int id){int no;for(int i = 0; i < 100; i++) {no = Counter++;order[no] = id;}}int main(int argc, char* argv[]){    vector<thread> threads;//建立多線程訪問計數器    for (int i = 0; i != 4; ++i)    //線程工作函數與線程標記參數        threads.push_back(thread(work, i));    for (auto & th:threads)        th.join();    //最終的計數值    cout << "final :" << Counter << endl;    //觀察各線程的工作時序    for(int i = 0; i < 400; i++)cout << "[" << i << "]=" << order[i] << " ";    return 0;}
注意編譯命令的參數,尤其,-lpthread

否則,若無該連結參數,則編譯不會出錯,但會發生執行階段錯誤:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
已放棄 (核心已轉儲)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.