c++ - 此代码打印的 x 值约为 5000 而不是 10000,这是为什么呢?

标签 c++ parallel-processing openmp

我编写的这段代码创建了 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/

相关文章:

c++ - 使用std::unique_ptr会产生无效的指针错误是怎么回事?

Java并行处理数组

c++ - 如何停止 OpenMP 2.0 的并行区域

c++ - 如何从 openMP (C++) 中的线程生成子线程

c++ - 用 C++ 编写扑克手数计算器

c++ - 从外部代码调用时,CMDIFrameWnd::MDIGetActive 返回 null

R 连接到 EC2 实例以进行并行处理

c - 在 linux C 中使用 Pthread 进行数组分区

c++ - 使用 OpenMP 的并发和优化

c++ - 多级/多继承期间对象的大小