我在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/