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

創(chuàng)新互聯(lián)建站專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、綏陽網(wǎng)絡(luò)推廣、微信小程序開發(fā)、綏陽網(wǎng)絡(luò)營(yíng)銷、綏陽企業(yè)策劃、綏陽品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)建站為所有大學(xué)生創(chuàng)業(yè)者提供綏陽建站搭建服務(wù),24小時(shí)服務(wù)熱線:18980820575,官方網(wǎng)址:www.cdcxhl.com
以計(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
- #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)建多線程訪問計(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ǔ))
網(wǎng)頁題目:利用C++11特性實(shí)現(xiàn)多線程計(jì)數(shù)器
分享URL:http://fisionsoft.com.cn/article/cogoipe.html


咨詢
建站咨詢
