我想運行以下內容:
for (int index = 0; index < num; index )
我想用四個執行緒運行for回圈,執行緒按順序執行:0、1、2、3、4、5、6、7、8等......也就是說,執行緒正在作業index =n,(n 1),(n 2),(n 3)(以任何特定的順序,但始終以這種模式),我希望迭代index = 0,1,2,...(n-1)已經完成。有沒有辦法做到這一點?Ordered 在這里并沒有真正起作用,因為使主體成為有序部分基本上會為我消除所有并行性,并且調度似乎不起作用,因為我不希望執行緒在執行緒 k->k index/ 上作業4. 謝謝你的幫助!
uj5u.com熱心網友回復:
您可以這樣做,而不是并行 for 回圈,而是在內部管理自己的回圈的并行區域,加上一個屏障,以確保所有正在運行的執行緒在能夠繼續之前都在其中達到相同的點。例子:
#include <stdatomic.h>
#include <stdio.h>
#include <omp.h>
int main()
{
atomic_int chunk = 0;
int num = 12;
int nthreads = 4;
omp_set_num_threads(nthreads);
#pragma omp parallel shared(chunk, num, nthreads)
{
for (int index; (index = atomic_fetch_add(&chunk, 1)) < num; ) {
printf("In index %d\n", index);
fflush(stdout);
#pragma omp barrier
// For illustrative purposes only; not needed in real code
#pragma omp single
{
puts("After barrier");
fflush(stdout);
}
}
}
puts("Done");
return 0;
}
一種可能的輸出:
$ gcc -std=c11 -O -fopenmp -Wall -Wextra demo.c
$ ./a.out
In index 2
In index 3
In index 1
In index 0
After barrier
In index 4
In index 6
In index 5
In index 7
After barrier
In index 10
In index 9
In index 8
In index 11
After barrier
Done
uj5u.com熱心網友回復:
我不確定我是否正確理解了您的要求。如果我試圖總結我是如何解釋它的,那將是這樣的:“我希望 4 個執行緒共享一個回圈的迭代,并且總是 4 個執行緒最多在回圈的 4 次連續迭代中運行”。
如果這就是你想要的,那么像這樣的東西呢:
int nths = 4;
#pragma omp parallel num_thread( nths )
for( int index_outer = 0; index_outer < num; index_outer = nths ) {
int end = min( index_outer nths, num );
#pragma omp for
for( int index = index_outer; index < end; index ) {
// the loop body just as before
} // there's a thread synchronization here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486661.html
