gpt4 book ai didi

c++ - 在没有互斥锁的 C++11 中实现共享整数计数器的最简单方法 :

转载 作者:IT老高 更新时间:2023-10-28 21:43:14 32 4
gpt4 key购买 nike

假设我们有以下代码来计算某事发生的次数:

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';
}

就目前而言,i 上有一个明确的竞争条件。使用 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";
}

最佳答案

您可能想查看 atomic types .您无需锁定/互斥即可访问它们。

关于c++ - 在没有互斥锁的 C++11 中实现共享整数计数器的最简单方法 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21835106/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com