14

「#pragmaompparallel num_threads(4)」を使用すると、異なるスレッドIDが取得されないのはなぜですか。この場合、すべてのスレッドIDは0です。しかし、行にコメントを付けてデフォルトのスレッド数を使用すると、異なるスレッドIDが取得されました。注:-変数スレッドIDを取得するために変数tidを使用しました。

#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
4

2 に答える 2

14

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()最も内側の領域のスレッド数を返します。つまり、4つのスレッドを実行しており、それぞれが1つのスレッドを実行しています。

ネストされた並列処理を有効にしていないため、内部並列領域は1つのスレッドのみを実行しています。を呼び出すことで有効にできますomp_set_nested(1)

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

2つのネストされた並列領域を作成する代わりに、1つの並列領域を作成し、2つのプロパティを指定する場合は、次のように実行できます。

#pragma omp parallel num_threads(4) private(nthreads,tid)
{
  .
  .
  .
}
于 2012-11-03T14:18:52.813 に答える
0

ネストは、環境変数OMP_NESTEDをtrueに設定することによっても有効にできます。

于 2019-07-19T22:40:31.977 に答える