【平行運算】OpenMP教學(一) 基礎語法

OpenMP是一個跨平台的多執行緒實現,主執行緒(順序的執行指令)生成一系列的子執行緒,並將任務劃分給這些子執行緒進行執行。這些子執行緒並列的執行,由執行時環境將執行緒分配給不同的處理器。

要進行並列執行的代碼片段需要進行相應的標記,用預編譯指令使得在代碼片段被執行前生成執行緒,每個執行緒會分配一個 id,可以通過函式 (omp_get_thread_num()) 來獲得該值,該值是一個整數,主執行緒的 id 為 0。在並列化的代碼執行結束後,子執行緒 join 到主執行緒中,並繼續執行程式。 (from wikipedia)

完整程式碼

OpenMP 基礎語法

  • # pragma omp parallel
  • # pragma opm parallel num_threads()
  • omp_set_num_threads()
  • omp_get_thread_num()

OpenMP 範例程式 : Hello, world

  1. 要使用 OpenMP ,需先 #include
  2. # pragma omp parallel :告訴程式碼接下來要進入 multithreading 的模式
# === complile 編譯 ===
$ g++ -fopenmp example_basic_1.cpp -o example_basic_1.out
// ** 檔名 example_basic_1.cpp **
// 都會阿嬤 OpenMP 教學
// 都會阿嬤 https://weikaiwei.com

#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[])
{

    printf("Hello, world (Master)\n");

#pragma omp parallel
    {
        printf("Hi! (Multithreading)\n");
    }

    return 0;
}
# === 執行 execute===
$ ./example_basic_1.out

# === 輸出 output===
Hello, world (Master)
Hi! (Multithreading)
Hi! (Multithreading)
Hi! (Multithreading)
Hi! (Multithreading)

OpenMP 範例程式 : Thread Number

  1. # pragma opm parallel num_threads() : 可以在進入multithreading時設定執行緒的數量
  2. omp_set_num_threads() : 也可以使用此函式設定執行緒數量
  3. omp_get_thread_num() : 在 multithreading 時,取得當下執行的執行緒的 ID,如果設定執行緒是 4,則執行緒ID會是 0, 1, 2, 3
# === complile 編譯 ===
$ g++ -fopenmp example_basic_1.cpp -o example_basic_2.out
// ** 檔名 example_basic_2.cpp **
// 都會阿嬤 OpenMP 教學
// 都會阿嬤 https://weikaiwei.com

#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[])
{
#pragma omp parallel num_threads(4)
    {
        int ID = omp_get_thread_num();
        printf("Hi, I am thread number %d.\n", ID);
    }

    omp_set_num_threads(3);
#pragma omp parallel
    {
        int ID = omp_get_thread_num();
        printf("Hello, I am thread number %d.\n", ID);
    }
    return 0;
}
# === 執行 execute===
$ ./example_basic_2.out

# === 輸出 output===
Hi, I am thread number 3
Hi, I am thread number 1
Hi, I am thread number 2
Hi, I am thread number 0
Hello, I am thread number 1
Hello, I am thread number 2
Hello, I am thread number 0

留言討論區