2014-01-09 162 views
0

我是OpenMP的新手,我試圖編寫一個帶有並行for構造的小程序。我無法理解我的程序輸出。我不明白爲什麼線程3在1和2之前輸出輸出。有人可以給我一個解釋嗎?for「for」循環的OpenMP輸出

所以,程序是:

#pragma omp parallel for 
for (i = 0; i < 7; i++) { 
    printf("We are in thread number %d and are printing %d\n", 
     omp_get_thread_num(), i); 
} 

並且輸出是:

We are in thread number 0 and are printing 0 
We are in thread number 0 and are printing 1 
We are in thread number 3 and are printing 6 
We are in thread number 1 and are printing 2 
We are in thread number 1 and are printing 3 
We are in thread number 2 and are printing 4 
We are in thread number 2 and are printing 5 

我的處理器是英特爾(R)核心(TM)的i5-2410M CPU有4個核。

謝謝!

回答

1

OpenMP不保證不同線程執行語句的相對順序。 OpenMP將其留給程序員,以便在需要時強制執行此類排序。一般來說,它並不是必需的,在很多情況下甚至不需要,這就是爲什麼OpenMP的默認行爲照原樣。實施這種排序的成本在時間上可能很重要。

我建議你多次運行更大的測試,你應該觀察到事件的跨線程排序本質上是隨機的。

1

如果你想以打印,那麼你可以使用ordered構建

#pragma omp parallel for ordered 
for (i = 0; i < 7; i++) { 
    #pragma omp ordered 
    printf("We are in thread number %d and are printing %d\n", 
     omp_get_thread_num(), i); 
} 

我認爲這需要從更大的迭代線程等待那些具有較低的迭代,因此會對性能產生影響。你可以看到它在這裏使用http://bisqwit.iki.fi/story/howto/openmp/#ExampleCalculatingTheMandelbrotFractalInParallel 這使用ordered繪製Mandelbrot集作爲字符。比使用ordered更快的解決方案是將字符並行填充數組,然後連續繪製它們(嘗試使用代碼)。由於使用OpenMP進行性能調優,我從來沒有找到使用ordered的好理由,但我確定它在某處使用。