利用 C++ 11 特性实现多线程计数器

来源:互联网 发布:mac os x 系统升级 编辑:程序博客网 时间:2024/06/07 19:30

原文地址:http://developer.51cto.com/art/201503/469525.htm

许多并行计算程序,需要确定待计算数据的编号,或者说,多线程间通过编号而耦合。此时,通过利用C++ 11提供的atomic_?type类型,可实现多线程安全的计数器,从而,降低多线程间的耦合,以便于书写多线程程序。

AD:干货来了,不要等!WOT2015 北京站演讲PPT开放下载!

许多并行计算程序,需要确定待计算数据的编号,或者说,多线程间通过编号而耦合。此时,通过利用C++ 11提供的atomic_?type类型,可实现多线程安全的计数器,从而,降低多线程间的耦合,以便于书写多线程程序。

利用 C++ 11 特性实现多线程计数器

以计数器实现为例子,演示了多线程计数器的实现技术方法,代码如下:

  1. //目的: 测试利用C++ 11特性实现计数器的方法 
  2. //操作系统: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.     //创建多线程访问计数器 
  25.     for (int i = 0; i != 4; ++i) 
  26.         //线程工作函数与线程标记参数 
  27.         threads.push_back(thread(work, i)); 
  28.     for (auto & th:threads) 
  29.         th.join(); 
  30.     //最终的计数值 
  31.     cout << "final :" << Counter << endl; 
  32.     //观察各线程的工作时序 
  33.     for(int i = 0; i < 400; i++) 
  34.         cout << "[" << i << "]=" << order[i] << " "
  35.     return 0

注意编译命令的参数,尤其,-lpthread

否则,若无该链接参数,则编译不会出错,但会发生运行时错误:

terminate called after throwing an instance of ‘std::system_error’

what(): Enable multithreading to use std::thread: Operation not permitted

已放弃 (核心已转储)


0 0
原创粉丝点击