2012-02-13 1 views
2

私のコードのパラレルブロック内に、私はスレッドプライベート変数tidを参照しています。 tidがSECTIONS指令に割り当てられています。OpenMP SECTIONSディレクティブを使用すると、プライベート変数がガベージ値として出力されます

しかし、その値を表示すると、パラレルブロック内ではあるがセクションブロックの外ではガベージ値が返されます。

なぜガベージ値が得られますか?

omp parallelブロック外の変数にアクセスし、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)を与えたのですか?

+0

firstprivate(tid)としてそれを宣言するtid'が初期化されないことがあります 'ように見えますが、私はよOpenMPをよく知っている人はいません。 –

+0

あなたは何かを 'omp section 'として宣言していません。おそらく、未定義の動作がいくつか見つかりました。 – user7116

+0

セクションブロック内ではなくセクションブロック内にコードを書くことは許容されないのですか? – user602774

答えて

2
  1. あなたがスレッド内で、この、その値を使用するにはtid
  2. 並列ブロックする前に初期化する必要が pragma omp