在代码的并行 block 内,我引用了一个线程私有(private)变量tid
。 tid
在 SECTIONS 指令中分配。
但是,当我打印它的值时,我在并行 block 内但在节 block 外收到一个垃圾值。
为什么我得到的是垃圾值?
据我所知,如果您访问 omp parallel
block 之外的变量并且未定义为 lastprivate
,您通常会得到一个垃圾值。
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
/* 4 threads, 1 core */
int main (int argc, char *argv[])
{
int nthreads, tid;
/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(tid)
{
#pragma omp sections
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Inside sections %d \n" ,tid);
}
printf("Out of sections %d \n", tid );
#pragma omp single
{
printf("Inside single block %d \n" , tid);
}
} /* All threads join master thread and disband */
printf("Outside parallel block \n");
}
以下是我收到的输出:
Hello World from thread = 3
Inside sections 3
Out of sections 0
Inside single block 0
Out of sections 1
Out of sections 3
Out of sections -1078056856
Outside parallel block
为什么tid
给出那个垃圾值(-1078056856)?
最佳答案
- 您应该在并行 block 之前初始化
tid
- 要在线程内使用它的值,请将其声明为
pragma omp
中的firstprivate(tid)
关于c - 使用 OpenMP SECTIONS 指令时私有(private)变量打印为垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9263534/