gpt4 book ai didi

c - 使用 OpenMP SECTIONS 指令时私有(private)变量打印为垃圾值

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:47 25 4
gpt4 key购买 nike

在我的代码的并行 block 中,我引用了一个线程私有(private)变量 tidtid 在 SECTIONS 指令中分配。

但是,当我打印它的值时,我在 parallel block 内但在 sections 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)?

最佳答案

  1. 你应该在并行 block 之前初始化tid
  2. 要在线程中使用它的值,请在 pragma omp 中将其声明为 firstprivate(tid)

关于c - 使用 OpenMP SECTIONS 指令时私有(private)变量打印为垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9263534/

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