c++ - OpenMP for 循环忽略 num_threads 子句

标签 c++ visual-studio-2008 openmp

我在VS2008中有以下代码:

int i,j;
bool pr = false;
#pragma omp parallel for private(pr) num_threads(2)
for(i=0;i<PIC_X;i++)
{
    int rank = omp_get_thread_num();
    int count = omp_get_num_threads();
    if ( !pr )
    {
        printf_s("Hello from thread %d of %d\n", rank, count);
        pr = true;
    }
    for(j=0;j<PIC_Y;j++)
    {
        // do stuff
    }
}

(如果您想知道,不要尝试创建嵌套的 OpenMP 循环)。问题是,num_threads 子句没有任何作用:我只在输出中得到“Hello from thread 0 of 1”。我尝试使用 omp_set_num_threads(2)同样,无济于事。是什么赋予了?

最佳答案

您已将 pr 设置在并行区域之外,然后通过将 pr 放入 private 子句中将其设为私有(private)。这意味着每个线程都有一个pr,但私有(private)pr变量没有初始化。 pr 使用 firstprivate 而不是 private,以便初始化私有(private)变量。

但是,您认为循环计数器默认为私有(private)是不正确的。 (即变量 i)的工作共享(或规范)的循环计数器是私有(private)的(OMP V2.0 规范的构造第 2.4.1 节)。但是“j”不是。请参阅 OpenMP V2.0 规范(这是 Microsoft 在 VS2008 中支持的),第 2.7.2 节数据共享属性子句:

If a variable is visible when a parallel or work-sharing construct is encountered, and the variable is not specified in a sharing attribute clause or threadprivate directive, then the variable is shared. Static variables declared within the dynamic extent of a parallel region are shared. Heap allocated memory (for example, using malloc() in C or C++ or the new operator in C++) is shared. (The pointer to this memory, however, can be either private or shared.) Variables with automatic storage duration declared within the dynamic extent of a parallel region are private.



至于 omp_get_num_threads() 返回 1,我能想到的只是你没有在启用 OpenMP 标志的情况下编译它。

关于c++ - OpenMP for 循环忽略 num_threads 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4899700/

相关文章:

c# - 返回自定义类的 WCF 服务在 Reference.cs 中生成错误

asp.net-mvc - 将控制权传递给 View 后如何调试 ASP.NET MVC Controller ?

c++ - 为什么 C++ 数组创建会导致段错误?

具有私有(private)复制构造函数的 C++11 std::is_convertible 行为

c++ - 使用迭代器从 vector 中查找子字符串

TEXT 宏中的 C++ 字符串变量

visual-studio-2008 - Visual Studio 2008上的NuPack(NuGet)

c++ - C++ 对象数组上的 OpenMP for 循环

c++ - 如何使用 Eigen 和 OpenMP 最大化 CPU 使用率

c++ - 为什么大数输入会导致此代码计算 primeCounting 时产生运行时错误?