c - OpenMP:任务中的竞争条件

标签 c multithreading parallel-processing openmp

鉴于此代码示例,练习是使用任务将代码与 OpenMP 并行。这是一组项目,我们想要计算那些好的项目。

int count_good (item_t* item)
{
    int n = 0;
    while (item) {
       if (is_good(item))
          n++;
       item = item->next;
    }
    return n;
}

这不完全是家庭作业。这是为了准备考试。我的想法如下:

int count_good (item_t* item)
{
    int n = 0;
    while (item) {
       #pragma omp task
       {
       if (is_good(item))
          n++;
       }
       item = item->next;
    }
    #pragma omp taskwait
    return n;
}
...

int main ()
{
...
#pragma omp parallel
{
#pragma omp single
    count_good(some_times);
}
}

一个问题是n,它是单线程的私有(private)变量,但它可以同时由不同的任务增加。这会产生竞争条件吗?可以用#pragma omp critical来避免吗?

最佳答案

您可以使用reduction来计算“好”项目。以下代码将为您完成这项工作。您可能想阅读this for reductionthis for traversing linked list

int nCount = 0;
#pragma omp parallel reduction(+ : nCount)
{       
    for(struct item_t *listWalk = some_items; listWalk != NULL; 
      listWalk = listWalk->next)
    {
        #pragma omp single nowait
        {
            if( isGood(listWalk) ){
            nCount += 1;
            }
        }           
    }
}

关于c - OpenMP:任务中的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947157/

相关文章:

C函数声明

c - 自己的简单网络服务器不发送页面

Python 线程 : What am I missing?(task_done() 调用次数过多)

lambda - 通过 DTO 进行 lambda 表达式的流传输

c++ - 如何将 for 循环转换为 STL for_each 语句

c - 你如何在automake中设置库的顺序?

c - 使用 scanf 解析字符串时的奇怪行为

java - Java 分析中的线程与加载类

java - thanAccept() 不打印值

python - 如何处理在 Python 中并行运行的子进程的用户输入?