新聞中心
許多并行計算程序,需要確定待計算數(shù)據的編號,或者說,多線程間通過編號而耦合。此時,通過利用C++ 11提供的atomic_?type類型,可實現(xiàn)多線程安全的計數(shù)器,從而,降低多線程間的耦合,以便于書寫多線程程序。

創(chuàng)新互聯(lián)建站專注為客戶提供全方位的互聯(lián)網綜合服務,包含不限于網站設計、網站制作、綏陽網絡推廣、微信小程序開發(fā)、綏陽網絡營銷、綏陽企業(yè)策劃、綏陽品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)建站為所有大學生創(chuàng)業(yè)者提供綏陽建站搭建服務,24小時服務熱線:18980820575,官方網址:www.cdcxhl.com
以計數(shù)器實現(xiàn)為例子,演示了多線程計數(shù)器的實現(xiàn)技術方法,代碼如下:
- //目的: 測試利用C++ 11特性實現(xiàn)計數(shù)器的方法
- //操作系統(tǒng):ubuntu 14.04
- //publish_date: 2015-1-31
- //注意所使用的編譯命令: g++ -Wl,--no-as-needed -std=c++0x counter.cpp -lpthread
- #include
- #include
- #include
- #include
- 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
threads; - //創(chuàng)建多線程訪問計數(shù)器
- for (int i = 0; i != 4; ++i)
- //線程工作函數(shù)與線程標記參數(shù)
- threads.push_back(thread(work, i));
- for (auto & th:threads)
- th.join();
- //最終的計數(shù)值
- cout << "final :" << Counter << endl;
- //觀察各線程的工作時序
- for(int i = 0; i < 400; i++)
- cout << "[" << i << "]=" << order[i] << " ";
- return 0;
- }
注意編譯命令的參數(shù),尤其,-lpthread
否則,若無該鏈接參數(shù),則編譯不會出錯,但會發(fā)生運行時錯誤:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted
已放棄 (核心已轉儲)
文章標題:利用C++11特性實現(xiàn)多線程計數(shù)器
當前地址:http://www.5511xx.com/article/cogoipe.html


咨詢
建站咨詢
