gpt4 book ai didi

c - 使用 openmp 在 C 中进行并行编程

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

现在我正在学习使用 openmp 在 C 中进行并行编程,现在我偶然发现了以下问题。我有一个简单的 for 循环,我想将其并行化。使用 openmp,我认为下面的代码应该可以完成这项工作

unsigned long int teller_groot;
int boel = 0;
int k = 0;
int l = 1;
unsigned long int sum2;
int thread_id;
int nloops;

#pragma omp parallel private(thread_id, nloops)
{
sum2 = 0;
#pragma omp for
for (teller_groot=1000000; teller_groot<1000000000000; teller_groot++)
{
boel = 0;
for (int i = 0; i < 78498; i++)
{
if (floor(teller_groot / array[i]) == teller_groot / array[i])
{
boel = 1;
break;
}
}

if (boel == 0)
{
sum2 = sum2 + teller_groot;
}

if (sum2 >= 1000000000)
{
sum2 = sum2 - 1000000000;
}

if (k == 10000000)
{
printf("%d, ", l);
l++;
k = 0;
}

k++;
}

thread_id = omp_get_thread_num();

printf("Thread %d performed %d iterations of the loop.\n", thread_id, nloops);
}

代码

if (k == 10000000)
{
printf("%d, ",l);
l++;
k = 0;
}

k++;

只是让我知道我们在循环中有多远。如果我运行程序,它不会打印任何东西,这意味着它不会计算任何东西。那么代码有什么问题呢?谢谢。

最佳答案

您已经在 openmp for 循环之外声明了变量 k(以及其他变量)。当变量在并行区域之外声明时,默认情况下它们具有共享范围。这意味着您使用的所有线程都将检查并写入同一个 k 变量,这可能会导致竞争条件。

如果你想用不同的线程写入同一个变量 k,你可以使用锁或原子更新来产生你想要的行为。

否则,在并行区域开头的#pragma语句中将k声明为私有(private)变量:

#pragma omp parallel private(thread_id, nloops, k)

这里有一本很好的入门书:http://supercomputingblog.com/openmp/tutorial-parallel-for-loops-with-openmp/

关于c - 使用 openmp 在 C 中进行并行编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538212/

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