與您想要的最接近的是OpenMP任務,可用於OpenMP v3.0及更高版本的編譯器。它是這樣:
#pragma omp parallel
{
#pragma omp single
for (int i = 0; i < 50; i++)
{
doStuff();
#pragma omp task
callback(i);
}
}
這段代碼可以使毛在一個線程只能執行,它會創建將調用callback()
使用不同的參數50 OpenMP的任務。然後它會在退出並行區域之前等待所有任務完成。空閒線程將執行任務(可能是隨機的)。 OpenMP在每個並行區域的末尾施加了一個隱式屏障,因爲它的fork-join執行模型要求只有主線程在並行區域之外運行。
下面是一個示例程序(ompt.cpp
):
#include <stdio.h>
#include <unistd.h>
#include <omp.h>
void callback (int i)
{
printf("[%02d] Task stated with thread %d\n", i, omp_get_thread_num());
sleep(1);
printf("[%02d] Task finished\n", i);
}
int main (void)
{
#pragma omp parallel
{
#pragma omp single
for (int i = 0; i < 10; i++)
{
#pragma omp task
callback(i);
printf("Task %d created\n", i);
}
}
printf("Parallel region ended\n");
return 0;
}
編譯和執行:
$ g++ -fopenmp -o ompt.x ompt.cpp
$ OMP_NUM_THREADS=4 ./ompt.x
Task 0 created
Task 1 created
Task 2 created
[01] Task stated with thread 3
[02] Task stated with thread 2
Task 3 created
Task 4 created
Task 5 created
Task 6 created
Task 7 created
[00] Task stated with thread 1
Task 8 created
Task 9 created
[03] Task stated with thread 0
[01] Task finished
[02] Task finished
[05] Task stated with thread 2
[04] Task stated with thread 3
[00] Task finished
[06] Task stated with thread 1
[03] Task finished
[07] Task stated with thread 0
[05] Task finished
[08] Task stated with thread 2
[04] Task finished
[09] Task stated with thread 3
[06] Task finished
[07] Task finished
[08] Task finished
[09] Task finished
Parallel region ended
注意,任務不會在他們創建相同的順序執行。
GCC在4.4以前的版本中不支持OpenMP 3.0。無法識別OpenMP指令會被忽略和生成的可執行文件會在連續的代碼段:
$ g++-4.3 -fopenmp -o ompt.x ompt.cpp
$ OMP_NUM_THREADS=4 ./ompt.x
[00] Task stated with thread 3
[00] Task finished
Task 0 created
[01] Task stated with thread 3
[01] Task finished
Task 1 created
[02] Task stated with thread 3
[02] Task finished
Task 2 created
[03] Task stated with thread 3
[03] Task finished
Task 3 created
[04] Task stated with thread 3
[04] Task finished
Task 4 created
[05] Task stated with thread 3
[05] Task finished
Task 5 created
[06] Task stated with thread 3
[06] Task finished
Task 6 created
[07] Task stated with thread 3
[07] Task finished
Task 7 created
[08] Task stated with thread 3
[08] Task finished
Task 8 created
[09] Task stated with thread 3
[09] Task finished
Task 9 created
Parallel region ended
什麼升壓線程或QT線程? OpenMP適用於數值計算,因爲與普通的線程框架相比,線程有很多開銷。如果你想要線程化,你將在使用線程框架方面取得更好的成功。 – tune2fs
OpenMP不起作用。你想要顯式的線程控制,OpenMP(特別是'parallel for'構造)全部關於*隱藏*顯式線程控制。 –
我想,由於數據依賴性,上面給出的示例不能完全按照這種方式完成。這個樣本很難判斷。您需要改變處理問題的方式,使其適用於OpenMP。見下文。 –