利用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
已放棄 (核心已轉儲)