#pragma omp parallel shared(newgrid,grid,maxdiff,epsilon) private(i,j,diff,maxdiff1,grid0,num_iter)
{
do{
#pragma omp critical
maxdiff = 0;
//num_iter=num_iter+1;
#pragma omp for
for (i=1;i<n;i++)
{
maxdiff1 = 0;
for (j=1;j<n;j++){
grid0 = grid[i+(n+1)*j];
newgrid[i+(n+1)*j] = (grid[i-1+(n+1)*j]+grid[i+1+(n+1)*j]+grid[i+(n+1)*(j-1)]+grid[i+(n+1)*(j+1)]-h*h*f[i-1+(n-1)*(j-1)])/4;
diff = fabs(newgrid[i+(n+1)*j]-grid0);
grid[i+(n+1)*j] = newgrid[i+(n+1)*j];
if (diff>maxdiff1)
maxdiff1 = diff;
}
#pragma omp critical
if (maxdiff1 > maxdiff) maxdiff = maxdiff1;
}
}while(maxdiff>=epsilon);
}
初始化openmp每个do {} while()循环的内容我在循环之前创建theads并在线程之间并行化i循环。问题是它在2个线程上无法正常工作,但正确地在1上,并且它不时卡住。
答案 0 :(得分:0)
当您写信至newgrid
时,您有竞争条件。例如,当一个线程的i
与另一个线程的i-1
相同时(同样适用于j
)。如果要获得正确的结果,请在写入newgrid时使用临界区。
do {
maxdiff = 0;
#pragma omp for private(i,j, diff, maxdiff1, grid0)
for (i=1;i<n;i++) {
maxdiff1 = 0;
for (j=1;j<n;j++) {
grid0 = grid[i+(n+1)*j];
#pragma omp critical
newgrid[i+(n+1)*j] = (grid[i-1+(n+1)*j]+grid[i+1+(n+1)*j]+grid[i+(n+1)*(j-1)]+grid[i+(n+1)*(j+1)]-h*h*f[i-1+(n-1)*(j-1)])/4;
diff = fabs(newgrid[i+(n+1)*j]-grid0);
grid[i+(n+1)*j] = newgrid[i+(n+1)*j];
if (diff>maxdiff1)
maxdiff1 = diff;
}
#pragma omp critical
if (maxdiff1 > maxdiff) maxdiff = maxdiff1;
}
}while(maxdiff>=epsilon);