2012-11-03 41 views
14

爲什麼我沒有得到不同的線程ID,當我使用「的#pragma OMP並行NUM_THREADS(4)」。在這種情況下,所有的線程ID都是0。 但是,當我評論該行並使用默認線程數時,我得到了不同的線程ID。 注意: - 變量我使用變量tid來獲取線程ID。的OpenMP:爲什麼我沒有得到不同的線程ID,當我使用「的#pragma OMP並行NUM_THREADS(4)」

#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 
+0

注: - 編制我做 gcc -fopenmp open.c -o你好 –

回答

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

我試過「#pragma omp_set_nested(1)」,但它不工作。 我正在寫上「#pragma omp parallel num_threads(4)」,我錯了? –

+1

@jayeshhathila:omp_set_nested()是一個常規函數 –

+0

我也得到了tid = 0的原因謝謝 –

相關問題