openMP:当我使用“#pragma omp parallel num_threads(4)”时,为什么我得不到不同的线程ID

时间:2012-11-03 13:35:57

标签: 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

2 个答案:

答案 0 :(得分:14)

您正在创建两个嵌套的并行区域。这与此相同:

#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)
{
  .
  .
  .
}

答案 1 :(得分:0)

也可以通过将环境变量OMP_NESTED设置为true来启用嵌套