我正在使用MPI对特定功能执行一些计算。我只需要针对该特定功能的MPI,所以我的问题是,当我在主功能中初始化MPI时,如何确保所编写的任何代码仅由等级为0的进程执行。
我尝试将所有内容放在if (rank == 0)
下,但是代码似乎无法正常工作。
int main(int argc, char* argv[])
{
int num_procs, my_id;
int *count, *disp;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
int i, j, N, k;
double u, l, h;
double *A, *b1, *b2, *x, *xo, x1bound, x2bound, y1bound, y2bound;
double norm, sum, dot, tmp;
l = -10;
u = 10;
h = 0.5;
tmp = (u-l)/h;
N = floor(tmp);
A = (double*)calloc(N*N,sizeof(double));
b1 = (double *)calloc(N,sizeof(double));
x = (double *)malloc(sizeof(double)*N);
xo = (double *)malloc(N*sizeof(double));
for (i = 0; i < N; i++)
xo[i] = 0.0;
count = (int*) calloc(num_procs, sizeof(int));
disp = (int*) calloc(num_procs, sizeof(int));
A[0] = -2.0;
A[1] = 1.0;
for (i = 1; i < N; i++)
{
A[i*N+i] = -2.0;
A[i*N+i+1] = 1.0;
A[i*N+i-1] = 1.0;
}
for (i = 0; i < N; i++)
b1[i] = (l + i*h);
func(&b1, N, h);
x1bound = 0;
y1bound = 0;
x2bound = 1;
y2bound = 0;
i = index_of(x1bound, l, h);
A[i*N+i] = 1.0;
A[i*N+i+1] = 0.0;
A[i*N+i-1] = 0.0;
b1[i] = y1bound;
i = index_of(x2bound, l, h);
A[i*N+i] = 1.0;
A[i*N+i+1] = 0.0;
A[i*N+i-1] = 0.0;
b1[i] = y2bound;
k = 0;
norm = INF;
while (norm > EPS)
{
dot = 0.0;
MATVEC(N,N,A,xo,&b2,num_procs,my_id,count,disp,MPI_COMM_WORLD);
for (i = 0; i < N; i++)
{
x[i] = (b1[i] - b2[i])/(A[i*N+i]);
dot += (x[i] - xo[i])*(x[i] - xo[i]);
}
for (i = 0; i < N; i++)
xo[i] = x[i];
printf("from %d dot = %lf\n",my_id,dot);
norm = sqrt(dot);
k++;
MPI_Bcast(xo,N,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
}
if(my_id == 0);
{
printf("After %d operations we obtained\n", k);
for(i = 0; i < N; i++)
printf("%lf\n", x[i]);
free(x); free(xo);
free(b1); free(b2);
free(A);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}