gpt4 book ai didi

c - 带有 Visual Studio 的 OpenMP : race condition

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:52 25 4
gpt4 key购买 nike

我最近尝试在 Visual Studio 中尝试使用 OpenMP 来学习如何对我的程序进行多线程处理。

如果我尝试串行执行此代码:

int totalSum = 0;

for(int x=0; x < 100; x++)
{
for(int y=0; y < 100; y++)
{
totalSum = totalSum + x + y;
}
}

我最终得到的是 totalSum = 990000

当我尝试通过以下方式仅添加 OpenMP 功能时:

#pragma omp parallel for
for(int x=0; x < 100; x++)
{

for(int y=0; y < 100; y++)
{
totalSum = totalSum + x + y;
}
}

我最终得到 totalSum = 491293 或 596865 或 638260 等...

显然发生的情况是竞争条件似乎正在发生,并且取决于哪个线程首先访问 totalSum,最终答案会有所不同。

我做错了什么? x 和 y 被正确定义为私有(private)变量(因为它们是在并行区域内创建的)。

与串行执行程序相比,我如何才能确保在多线程程序时得到相同的答案?

最佳答案

解决方法是使用reduction 子句:

int totalSum = 0;

#pragma omp parallel for reduction(+:totalSum) // reduction
for(int x=0; x < 100; x++)
{

for(int y=0; y < 100; y++)
{
totalSum = totalSum + x + y;
}
}

阅读 OpenMP 缩减条款,然后您就会了解它是如何工作的。

关于c - 带有 Visual Studio 的 OpenMP : race condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301897/

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