第一篇就用最簡單的教學吧
首先就是在GUN上要怎麼把OpenMP編譯進去
$ g++ filenamie.cpp -fopenmp
如果不加上-fopenmp的話,編譯器會自動把openmp的語法都忽略掉。
以下開始進行測試
#include
#include
#include
int main()
{
for (int i = 0; i < 8; i++) {
printf("thread [%d]: print number %d\n", omp_get_thread_num(), i);
}
return 0;
}
結果是:
thread [0]: print number 0
thread [0]: print number 1
thread [0]: print number 2
thread [0]: print number 3
thread [0]: print number 4
thread [0]: print number 5
thread [0]: print number 6
thread [0]: print number 7
omp_get_thread_num()語法是告知現在是那個執行緒,最簡單的想法就是他安排那一個CPU在跑這段語法
明顯看到,就是我們一般單執行緒的寫法。
接著加上openmp平行的寫法
#include
#include
#include
int main()
{
#pragma omp parallel for
for (int i = 0; i < 8; i++) {
printf("thread [%d]: print number %d\n", omp_get_thread_num(), i);
}
return 0;
}
結果是:
thread [1]: print number 2
thread [1]: print number 3
thread [0]: print number 0
thread [0]: print number 1
thread [2]: print number 4
thread [2]: print number 5
thread [3]: print number 6
thread [3]: print number 7
可以看到,這個for變的不是單一執行緒在執行,而是不同的CPU在上面跑
所以出來的結果就不是如第一段相同。
最後再來看看
#include
#include
#include
int main()
{
#pragma omp parallel
for (int i = 0; i < 8; i++) {
printf("thread [%d]: print number %d\n", omp_get_thread_num(), i);
}
return 0;
}
結果會是:
thread [2]: print number 0
thread [2]: print number 1
thread [2]: print number 2
thread [2]: print number 3
thread [2]: print number 4
thread [2]: print number 5
thread [2]: print number 6
thread [2]: print number 7
thread [1]: print number 0
thread [1]: print number 1
thread [1]: print number 2
thread [1]: print number 3
thread [1]: print number 4
thread [1]: print number 5
thread [1]: print number 6
thread [1]: print number 7
thread [3]: print number 0
thread [3]: print number 1
thread [3]: print number 2
thread [3]: print number 3
thread [3]: print number 4
thread [3]: print number 5
thread [3]: print number 6
thread [3]: print number 7
thread [0]: print number 0
thread [0]: print number 1
thread [0]: print number 2
thread [0]: print number 3
thread [0]: print number 4
thread [0]: print number 5
thread [0]: print number 6
thread [0]: print number 7
目前就先寫到這,因為還有很多不懂的地方
沒有留言:
張貼留言