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

标签 c openmp

在代码的并行 block 内,我引用了一个线程私有(private)变量tidtid 在 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)?

最佳答案

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

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

相关文章:

c - 理解指针

c - 将 void * 缓冲区用作 char * 以外的任何缓冲区是否合法?

c++ - 如何剖析 OpenMP 瓶颈

c++ - 基于并行位操作的 openMP 素数查找器?

c++ - std::lock_guard 在 openmp 并行

gcc - 对 `omp_get_max_threads_' 的 undefined reference

multithreading - 用于蒙特卡洛集成的线程安全随机数生成

c - 在 C 中发送/接收 SOAP 请求/响应

c - 系统崩溃时 clflush 或 clflushopt 是原子的吗?

c - 将 64 位十六进制地址中的位提取到 C 中的无符号整数中