c - openMP:为什么我在使用 "#pragma omp parallel num_threads(4)"时没有得到不同的线程 ID

标签 c multithreading parallel-processing openmp

为什么我在使用“#pragma omp parallel num_threads(4)”时没有得到不同的线程 ID。在这种情况下,所有线程 ID 都是 0。 但是当我评论该行并使用默认线程数时,我得到了不同的线程 ID。 注意:- 变量我使用变量 tid 来获取线程 ID。

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) 
{
int nthreads, tid;
int x = 0;

#pragma omp parallel num_threads(4)
#pragma omp parallel private(nthreads, tid)
  {
  /* 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);
     }

  }


}

以上代码的输出:-

Hello World from thread = 0
Hello World from thread = 0
Number of threads = 1
Hello World from thread = 0
Number of threads = 1
Hello World from thread = 0
Number of threads = 1
Number of threads = 1

当我评论上面提到的行时的输出:-

Hello World from thread = 3
Hello World from thread = 0
Number of threads = 4
Hello World from thread = 1
Hello World from thread = 2

最佳答案

您正在创建两个嵌套的平行区域。这与这样做是一样的:

#pragma omp parallel num_threads(4)
{
  #pragma omp parallel private(nthreads, tid)
  {
    /* 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);
    }
  }
}

omp_get_num_threads() 返回最里面区域的线程数。因此,您正在执行四个线程,每个线程都在执行一个线程。

内部并行区域只执行一个线程,因为您还没有启用嵌套并行。您可以通过调用 omp_set_nested(1) 来启用它。

http://docs.oracle.com/cd/E19205-01/819-5270/aewbi/index.html

如果您不想制作两个嵌套的平行区域,而是想要制作一个平行区域并指定两个属性,您可以这样做:

#pragma omp parallel num_threads(4) private(nthreads,tid)
{
  .
  .
  .
}

关于c - openMP:为什么我在使用 "#pragma omp parallel num_threads(4)"时没有得到不同的线程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13209686/

相关文章:

c - 将节点添加到哈希表

c# - 如何制作具有连续 ID 的线程

Java - 终止线程中的方法

java - 如何从Java中的线程获取所有子线程?

c - 如何在 openssl 中将证书文件转换为 const char certBuffer[CERTIFICATE_SIZE]?

c++ - 'else'编程需要空 'safe'语句吗?

c++ - 如何进行并行双线性插值

c# - Parallel.ForEach - 它在单核机器上运行在哪里?

c - fscanf 是否向后移动文件指针?

c++ - 我如何在 Xcode 中使用 mpi.h?