我試圖理解為什么需要障礙來消除比賽條件?
#include<omp.h>
#include<stdio.h>
int main()
{
int sum = 0;
#pragma omp parallel num_threads(4)
for(int i = 0;i < 10;i )
{
#pragma omp parallel for num_threads(4)
for(int j = 0;j < 10;j )
{
#pragma omp critical
sum = 1;
}
// Uncommenting this barrier removes the race condition. Right now it is non-deterministic.
// #pragma omp barrier
#pragma omp single
sum = 1;
}
printf("%d", sum);
}
uj5u.com熱心網友回復:
如果沒有“pragma omp barrier”,另一個執行緒可能同時訪問“pragma omp critical”部分內的同一個sum變數。這將導致不確定的結果。
屏障強制所有執行緒完成內部 for 回圈,然后單個執行緒可以繼續執行最后一部分,而不會有任何競爭條件的風險。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518365.html
標籤:C并行处理开放式竞争条件
