gpt4 book ai didi

c - 使用默认(私有(private))子句时出现 OpenMP 错误

转载 作者:行者123 更新时间:2023-11-30 14:43:40 25 4
gpt4 key购买 nike

我的代码出现错误,该代码应该使用随机点计算 Pi。

错误:“私有(private)”:OpenMP“默认”子句中的参数无效

代码:

int main()
{
int npoints = 2000;
int num_threads;
int sample_points_per_thread;
double rand_no_x;
double rand_no_y;
int sum;
#pragma omp parallel default(private) shared(npoints) reduction(+: sum) num_threads(8)
{
num_threads = omp_get_num_threads();
sample_points_per_thread = npoints / num_threads;
sum = 0;
for (int i = 0; i < sample_points_per_thread; i++) {
rand_no_x = (double)(rand() / (double)(RAND_MAX));
rand_no_y = (double)(rand() / (double)(RAND_MAX));
if (((rand_no_x - 0.5) * (rand_no_x - 0.5) + (rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25)
sum++;
}
}
printf(sum / npoints);
}

最佳答案

根据文档:

default(shared|none);
Controls the default data-sharing attributes of
variables that are referenced in a parallel or task
construct.

shared(list);
Declares one or more list items to be shared by tasks
generated by a parallel or task construct.

private(list);
Declares one or more list items to be private to a task.

这是一个工作代码示例:然而,这可能可以通过更好的方式来完成。

int main()
{
int npoints = 2000;
int sum = 0;
double rand_no_x;
double rand_no_y;
int num_threads;
int sample_points_per_thread;

srand((unsigned int)time(0));

#pragma omp parallel default(none) private(rand_no_x, rand_no_y, num_threads, sample_points_per_thread) shared(npoints) reduction(+: sum) num_threads(8)
{
num_threads = omp_get_num_threads();
sample_points_per_thread = npoints / num_threads;

sum = 0;
for (int i = 0; i < sample_points_per_thread; i++) {
rand_no_x = (double)rand() / (double)RAND_MAX;
rand_no_y = (double)rand() / (double)RAND_MAX;
if (((rand_no_x - 0.5) * (rand_no_x - 0.5) + (rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25) {
sum = sum + 1;
}
}
}
printf("%f\n", (4.0 * (double)sum) / (double)npoints);
}

关于c - 使用默认(私有(private))子句时出现 OpenMP 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53811658/

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