for循环内的openmp临界区

openmp critical section inside for loop

我有以下代码更新 for 循环内的内容,然后是另一个 for 循环。但是,我在第二个循环开始时收到错误:"expected a declaration"。问题似乎出在 "critical" 部分,因为如果我删除它,错误就会消失。我是 openMP 的新手,我在这里遵循一个示例:http://www.viva64.com/en/a/0054/#ID0EBUEM(请参阅“5.关键部分的条目太多”)。有人知道我在这里做错了什么吗?

另外,"If the comparison is performed before the critical section, the critical section will not be entered during all iterations of the loop"是真的吗?

还有一点就是其实我想同时并行化两个循环,但是由于循环内部的操作不同,所以我这里使用了两个线程组,希望如果里面有不需要的线程第一个循环,他们可以立即开始执行第二个循环。这行得通吗?

double maxValue = 0.0;
#pragma omp parallel for schedule (dynamic) //first loop
    for (int i = 0; i < n; i++){
        if (some condition satisfied)
        {
            #pragma omp atomic
            count++;
            continue;
        }

        double tmp = getValue(i);

        #pragma omp flush(maxValue)
        if (tmp > maxValue){
            #pragma omp critical(updateMaxValue){
            if (tmp > maxValue){
                maxValue = tmp;
                //update some other variables
                  ...
            }
            }
        }
    }
#pragma omp parallel for schedule (dynamic) //second loop
    for (int i = 0; i < m; i++){
       //some operations...
     }
#pragma omp barrier

抱歉,我有这么多问题,在此先感谢!

However, I got the error: "expected a declaration" at the beginning of the second loop.

您有语法错误 - 左大括号(如果存在)必须移至新行:

#pragma omp critical(updateMaxValue){
//                                 ~^~

应改为:

#pragma omp critical(updateMaxValue)
{

(您实际上不需要它,因为后面的 if 语句是一个 结构化块 )。


Another thing is that I actually want to parallelize the two loops at the same time, but since the operations inside the loops are different, I use two thread teams here, hoping that if there are threads that are not needed in the first loop, they can start executing the second loop immediately.

使用单个并行区域,然后在第一个 for 循环上使用 nowait 子句:

#pragma omp parallel
{
    #pragma omp for schedule(dynamic) nowait
    //                                ~~~~~^
    for (int i = 0; i < n; i++)
    {
        // ...
    }

    #pragma omp for schedule(dynamic)
    for (int i = 0; i < m; i++)
    {
        // ...
    }
}