利用 C++ 11 特性實現多線程計數器

jopen 11年前發布 | 15K 次閱讀 C/C++開發 C/C++

許多并行計算程序,需要確定待計算數據的編號,或者說,多線程間通過編號而耦合。此時,通過利用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; }</pre>

注意編譯命令的參數,尤其,-lpthread

否則,若無該鏈接參數,則編譯不會出錯,但會發生運行時錯誤:

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

來源:alaclp的專欄

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!