use*_*717 14 c++ multithreading c++11 stdatomic
假设我们有以下代码来计算出现事件的次数:
int i=0;
void f() {
// do stuff . . .
if(something_happens) ++i;
}
int main() {
std::vector<std::thread> threads;
for(int j = 0; j< std::thread::hardware_concurrency(); ++j) {
threads.push_back(std::thread(f));
}
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread_join));
std::cout << "i = " << i << '\n';
}
Run Code Online (Sandbox Code Playgroud)
目前看来我的竞争条件很明显.使用C++ 11,什么是(1)消除这种竞争条件的最简单方法,以及(2)最快的方法?,最好不使用互斥锁.谢谢.
更新:使用注释使用原子,我得到了一个工作程序,编译在英特尔编译器,版本13:
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <algorithm>
std::atomic<unsigned long long> i = 0;
void f(int j) {
if(j%2==0) {
++i;
}
}
int main() {
std::cout << "Atomic i = " << i << "\n";
int numThreads = 8; //std::thread::hardware_concurrency() not yet implemented by Intel
std::vector<std::thread> threads;
for(int k=0; k< numThreads; ++k) {
threads.push_back(std::thread(f, k));
}
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
std::cout << "Atomic i = " << i << "\n";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1675 次 |
| 最近记录: |