利用 C++ 11 特性實(shí)現(xiàn)多線程計(jì)數(shù)器
許多并行計(jì)算程序,需要確定待計(jì)算數(shù)據(jù)的編號(hào),或者說,多線程間通過編號(hào)而耦合。此時(shí),通過利用C++ 11提供的atomic_?type類型,可實(shí)現(xiàn)多線程安全的計(jì)數(shù)器,從而,降低多線程間的耦合,以便于書寫多線程程序。
以計(jì)數(shù)器實(shí)現(xiàn)為例子,演示了多線程計(jì)數(shù)器的實(shí)現(xiàn)技術(shù)方法,代碼如下:
- //目的: 測(cè)試?yán)肅++ 11特性實(shí)現(xiàn)計(jì)數(shù)器的方法
- //操作系統(tǒng):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;
- //創(chuàng)建多線程訪問計(jì)數(shù)器
- for (int i = 0; i != 4; ++i)
- //線程工作函數(shù)與線程標(biāo)記參數(shù)
- threads.push_back(thread(work, i));
- for (auto & th:threads)
- th.join();
- //最終的計(jì)數(shù)值
- cout << "final :" << Counter << endl;
- //觀察各線程的工作時(shí)序
- for(int i = 0; i < 400; i++)
- cout << "[" << i << "]=" << order[i] << " ";
- return 0;
- }
注意編譯命令的參數(shù),尤其,-lpthread
否則,若無該鏈接參數(shù),則編譯不會(huì)出錯(cuò),但會(huì)發(fā)生運(yùn)行時(shí)錯(cuò)誤:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted
已放棄 (核心已轉(zhuǎn)儲(chǔ))