// ** 檔名 example_synchronization_1.cpp **
#include <stdio.h>
#include <omp.h>
int main()
{
printf("Case 1, without barrier:\n");
#pragma omp parallel num_threads(2)
{
const int thread_id = omp_get_thread_num();
// Case 1, without barrier
printf("A1 I am thread %d\n", thread_id);
printf("A2 I am thread %d\n", thread_id);
printf("B I am thread %d\n", thread_id);
}
printf("\n=======================\n\n");
printf("Case 2, with barrier:\n");
#pragma omp parallel num_threads(2)
{
const int thread_id = omp_get_thread_num();
// Case 2, with barrier
printf("A1 I am thread %d\n", thread_id);
printf("A2 I am thread %d\n", thread_id);
#pragma omp barrier
printf("B I am thread %d\n", thread_id);
}
return 0;
}
# === 執行 execute===
$ ./example_synchronization_1.out
# === 輸出 output===
Case 1, without barrier:
A1 I am thread 1
A2 I am thread 1
B I am thread 1
A1 I am thread 0
A2 I am thread 0
B I am thread 0
=======================
Case 2, with barrier:
A1 I am thread 1
A2 I am thread 1
A1 I am thread 0
A2 I am thread 0
B I am thread 1
B I am thread 0
// ** 檔名 example_synchronization_2.cpp **
// 都會阿嬤 OpenMP 教學
// 都會阿嬤 https://weikaiwei.com
#include <stdio.h>
#include <omp.h>
int main()
{
// Case 1, without critical
int number = 0;
#pragma omp parallel num_threads(2)
{
#pragma omp for
for (int i = 0; i < 10000; i++)
{
number++;
}
#pragma omp single // just print once
printf("Without critical, the number is :%d\n", number); // wrong because of data race
}
// Case 2, with critical
number = 0;
#pragma omp parallel num_threads(2)
{
#pragma omp for
for (int i = 0; i < 10000; i++)
{
#pragma omp critical
{
number++;
}
}
#pragma omp single // just print once
printf("With critical, the number is :%d\n", number); // correct because of data race
}
return 0;
}
# === 執行 execute===
$ ./example_synchronization_2.out
# === 輸出 output===
Without critical, the number is :5275
With critical, the number is :10000
OpenMP 範例程式 : ordered 順序
# pragma omp ordered : 搭配 # pragma omp for ordered 使用,放在 for region 裡面,# pragma omp ordered 指定 for loop 裡面要被順序執行的區塊,
// ** 檔名 example_synchronization_3.cpp **
// 都會阿嬤 OpenMP 教學
// 都會阿嬤 https://weikaiwei.com
#include <stdio.h>
#include <omp.h>
int main()
{
const int N = 8;
int A[N] = {1, 2, 3, 4, 5, 6, 7, 8};
#pragma omp parallel
{
const int thread_id = omp_get_thread_num();
#pragma omp for ordered
for (int i = 0; i < N; i++)
{
#pragma omp ordered
{
A[i] = A[i] + 1;
printf("A[%d] is computed by thread : %d\n", i, thread_id);
}
}
}
return 0;
}
# === 執行 execute===
$ ./example_synchronization_3.out
# === 輸出 output===
A[0] is computed by thread : 0
A[1] is computed by thread : 0
A[2] is computed by thread : 1
A[3] is computed by thread : 1
A[4] is computed by thread : 2
A[5] is computed by thread : 2
A[6] is computed by thread : 3
A[7] is computed by thread : 3