利用 C++ 11 特性实现多线程计数器
2015-01-31 00:00
477 查看
许多并行计算程序,需要确定待计算数据的编号,或者说,多线程间通过编号而耦合。此时,通过利用C++ 11提供的atomic_?type类型,可实现多线程安全的计数器,从而,降低多线程间的耦合,以便于书写多线程程序。
以计数器实现为例子,演示了多线程计数器的实现技术方法,代码如下:
注意编译命令的参数,尤其,-lpthread
否则,若无该链接参数,则编译不会出错,但会发生运行时错误:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted
已放弃 (核心已转储)
以计数器实现为例子,演示了多线程计数器的实现技术方法,代码如下:
//目的: 测试利用C++ 11特性实现计数器的方法 //操作系统:ubuntu 14.04 //publish_date: 2015-1-31 //注意所使用的编译命令: g++ -Wl,--no-as-needed -std=c++0x counter.cpp -lpthread #include <iostream> #include <atomic> #include <thread> #include <vector> 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<thread> threads; //创建多线程访问计数器 for (int i = 0; i != 4; ++i) //线程工作函数与线程标记参数 threads.push_back(thread(work, i)); for (auto & th:threads) th.join(); //最终的计数值 cout << "final :" << Counter << endl; //观察各线程的工作时序 for(int i = 0; i < 400; i++) cout << "[" << i << "]=" << order[i] << " "; return 0; }
注意编译命令的参数,尤其,-lpthread
否则,若无该链接参数,则编译不会出错,但会发生运行时错误:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted
已放弃 (核心已转储)
相关文章推荐
- 利用 C++ 11 特性实现多线程计数器
- 利用C++ 11特性实现多线程计数器
- C++ 11新特性之用多线程实现生产者消费者问题
- C++中利用多线程实现定时器
- 利用Boost实现高度可移植的多线程C++程序
- C++中利用多线程实现定时器
- C++中利用多线程实现定时器
- 【javac添加python 列表特性11】利用修改后的javac实现快速排序
- C++中利用多线程实现定时器
- 巧妙的利用C++的特性实现Profiling
- c++利用winapi实现简单多线程
- C#中利用委托实现多线程跨线程操作
- 从易到难编写C++程序,(6)问题:利用问题(5)的随机数生成实现发牌
- 请教高手:如何利用Delphi实现多线程圆周率的计算
- 从易到难编写C++程序,(7)问题:利用问题(6)的发牌,实现24点游戏
- C++面向对象特性实现机制的初步分析 Part3
- 利用JScript中运算符"||"和"&&"的特殊特性实现代码精简第1/2页
- 利用sql2005的新特性实现根据子表条件得到的主表键且按其排序取出对应主表记录的方法
- 在c++中利用指针实现动态数组
- 利用JScript中运算符"||"和"&&"的特殊特性实现代码精简第1/2页