自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

利用 C++ 11 特性實(shí)現(xiàn)多線程計(jì)數(shù)器

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

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

利用 C++ 11 特性實(shí)現(xiàn)多線程計(jì)數(shù)器

以計(jì)數(shù)器實(shí)現(xiàn)為例子,演示了多線程計(jì)數(shù)器的實(shí)現(xiàn)技術(shù)方法,代碼如下:

  1. //目的: 測(cè)試?yán)肅++ 11特性實(shí)現(xiàn)計(jì)數(shù)器的方法 
  2. //操作系統(tǒng):ubuntu 14.04 
  3. //publish_date: 2015-1-31 
  4. //注意所使用的編譯命令: g++ -Wl,--no-as-needed -std=c++0x counter.cpp -lpthread 
  5. #include <iostream> 
  6. #include <atomic> 
  7. #include <thread> 
  8. #include <vector> 
  9.  
  10. using namespace std; 
  11.  
  12. atomic_int Counter(0); 
  13. int order[400]; 
  14.  
  15. void work(int id) 
  16.     int no; 
  17.     for(int i = 0; i < 100; i++) { 
  18.         no = Counter++; 
  19.         order[no] = id; 
  20.     } 
  21.  
  22. int main(int argc, char* argv[]) 
  23.     vector<thread> threads; 
  24.     //創(chuàng)建多線程訪問計(jì)數(shù)器 
  25.     for (int i = 0; i != 4; ++i) 
  26.         //線程工作函數(shù)與線程標(biāo)記參數(shù) 
  27.         threads.push_back(thread(work, i)); 
  28.     for (auto & th:threads) 
  29.         th.join(); 
  30.     //最終的計(jì)數(shù)值 
  31.     cout << "final :" << Counter << endl; 
  32.     //觀察各線程的工作時(shí)序 
  33.     for(int i = 0; i < 400; i++) 
  34.         cout << "[" << i << "]=" << order[i] << " "
  35.     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ǔ))

責(zé)任編輯:王雪燕 來源: alaclp的專欄
相關(guān)推薦

2023-08-08 08:01:22

微服務(wù)架構(gòu)服務(wù)

2022-09-08 06:23:37

C++HTTP 服務(wù)器

2011-04-06 10:03:08

Cacti遠(yuǎn)程監(jiān)控

2011-03-31 16:03:20

cacti性能計(jì)數(shù)器

2012-05-18 10:36:20

CC++編程

2013-03-18 09:42:47

C++C++ 11

2010-01-18 14:09:58

C++多線程

2010-02-04 10:19:39

C++多線程

2010-02-05 15:30:54

C++多線程測(cè)試

2021-02-25 15:58:46

C++線程編程開發(fā)技術(shù)

2021-03-05 07:38:52

C++線程編程開發(fā)技術(shù)

2009-12-01 15:01:07

PHP生成訪問計(jì)數(shù)器

2020-06-28 11:14:36

多線程性能結(jié)構(gòu)

2009-11-06 16:59:26

WCF性能計(jì)數(shù)器

2023-07-28 08:15:27

PC程序計(jì)數(shù)器

2024-06-24 08:10:00

C++互斥鎖

2009-07-16 10:20:21

赫夫曼編碼

2024-11-05 16:29:57

2023-12-14 15:05:08

volatile代碼C++

2009-10-29 11:47:15

ADO.NET計(jì)數(shù)器b
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)