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

标签 c openmp

我的代码出现错误,该代码应该使用随机点计算 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/

相关文章:

c - ANSI C 中的之字形数组

c - 如何理解数组中的this指针?

c++ - 计算文件中的 react 数

c++ - GCC 8.1.0/MinGW64 编译的 OpenMP 程序崩溃寻找 cygwin.s?

c++ - g++ stringstream 构造函数是否有临界区?

python - python如何在数组中具有不同的数据类型?

c - 为什么换行符在导致该字符串的字符串之前的位置未得到打印?

c - 在 Cypress FX3 中初始化 gdb 调试器时出现以下错误

c++ - OpenMP undefined reference `_CRT_fenv' 和 `_setargv'

parallel-processing - OpenMP 程序比顺序程序慢