许多并行计算程序需要确定要计算的数据个数,或者说,多线程是由个数耦合的。这时候,通过使用C++11提供的atomic_?type类型,可以实现多线程安全的计数器,从而降低多线程之间的耦合度,让编写多线程程序变得更加简单。以计数器实现为例,演示多线程计数器的实现技术。代码如下://目的:测试利用C++11特性实现计??数器的方法。//操作系统:ubuntu14.04//publish_date:2015-1-31//注意使用的编译命令:g++-Wl,--no-as-needed-std=c++0xcounter.cpp-lpthread#include#include#include#includeusingnamespacestd;atomic_intCounter(0);intorder[400];voidwork(intid){intno;for(inti=0;i<100;i++){no=Counter++;order[no]=id;}}intmain(intargc,char*argv[]){vectorthreads;//创建多线程访问计数器for(inti=0;i!=4;++i)//线程工作函数和线程标记参数threads.push_back(thread(work,i));for(auto&th:threads)th.join();//最终计数值cout<<"final:"<