使用Visual Studio的OpenMP:竞争条件

时间:2012-11-09 03:56:34

标签: c visual-studio-2010 openmp

我最近尝试在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被正确定义为私有变量(因为它们是在并行区域内创建的)。

与串行执行程序相比,当我对程序进行多线程处理时,我能做些什么来确保得到相同的答案?

1 个答案:

答案 0 :(得分:2)

修复方法是使用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减少条款,然后您将了解它是如何工作的。

相关问题