鉴于此代码示例,练习是使用任务将代码与 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 reduction和 this 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/