我编写的这段代码创建了 2 个线程和一个迭代 10000 次的 for 循环,但最后 x 的值接近 5000 而不是 10000,为什么会这样?
#include<unistd.h>
#include<stdio.h>
#include<sys/time.h>
#include "omp.h"
using namespace std;
int x=0;
int main(){
omp_set_num_threads(2);
#pragma omp parallel for
for(int i= 0;i<10000;i++){
x+=1;
}
printf("x is: %d\n",x);
}
最佳答案
x
不是atomic 类型,并且在不同的线程中读取和写入。 (认为 int
是原子类型是一种常见的误解。)
因此,您的程序的行为是未定义。
使用 std::atomic<int> x;
是解决方法。
关于c++ - 此代码打印的 x 值约为 5000 而不是 10000,这是为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652219/