要徑
指定一次,程式碼只執行一個執行緒上。
#pragma omp critical [(name)]
{
code_block
}
備註
其中,
- (name) (optional)
識別關鍵的程式碼的名稱。 請注意該名稱必須以括號括住。
備註
要徑指示詞可支援任何 OpenMP 子句。
如需詳細資訊,請參閱 2.6.2 要徑建構。
範例
// omp_critical.cpp
// compile with: /openmp
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int i;
int max;
int a[SIZE];
for (i = 0; i < SIZE; i++)
{
a[i] = rand();
printf_s("%d\n", a[i]);
}
max = a[0];
#pragma omp parallel for num_threads(4)
for (i = 1; i < SIZE; i++)
{
if (a[i] > max)
{
#pragma omp critical
{
// compare a[i] and max again because max
// could have been changed by another thread after
// the comparison outside the critical section
if (a[i] > max)
max = a[i];
}
}
}
printf_s("max = %d\n", max);
}