我有一個9x9的2D數組。我用隨機數填充數組,然後發送數組的前3行用rank = 1進行處理,數組的第2個3行用rank = 2進行處理,最後發送數組的第3個3行進行處理秩= 3。我的意思是每個進程都會得到3行數組。並行計算2維數組的直方圖
在進程接收到主數組的各行之後,它將計算從根進程接收到的3行的直方圖。然後將直方圖返回到根進程。所有3個進程都將完成這項任務。
問題是,rank = 3的進程無法接收根進程發送的行。我無法弄清楚爲什麼? 如果有人看看我的代碼並找到解決問題的方法,我將不勝感激。
在此先感謝。
我正在使用MPI與c。這裏是我的代碼
#include "mpi.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int main(int argc, char* argv[])
{
int my_rank;
int p;
int i;
int k;
int m;
int tag=0;
int array[9][9];
int sub_array[3][9]; // 3 rows and 9 columns for each process
int c[20];
MPI_Status status;
// MPI_Datatype MPI_INT;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&p);
// MPI_Type_contiguous(9,MPI_INT,&MPI_INT);
// MPI_Type_commit(&MPI_INT);
srand(time(NULL));
for(i=0; i<20 ; i++)
c[i] = 0;
if(my_rank == 0)
{
for(i=0; i<9 ; i++)
for(k=0; k<9 ; k++)
{
array[i][k] = rand()%20+1; // fill the array with random numbers from 1 to 20;
}
for(i=0; i<9 ; i++)
{
printf("\n");
for(k=0; k<9 ; k++)
{
printf("%d ",array[i][k]); // prints the array here
}
}
// here each process will be sent 3 rows of the array;
for(i=0; i<3 ; i++)
MPI_Send(&(array[i][0]),9,MPI_INT,1,tag,MPI_COMM_WORLD); // 1st 3 rows of the array are sent to process 1
for(i=3; i<6 ; i++)
MPI_Send(&(array[i][0]),9,MPI_INT,2,tag,MPI_COMM_WORLD); // 2nd 3 rows of the array are sent to process 2
for(i=6; i<9 ; i++)
MPI_Send(&(array[i][0]),9,MPI_INT,3,tag,MPI_COMM_WORLD); // 3rd 3 rows of the array are sent to process 3
for (i=1;i<=3;i++)
MPI_Recv(&sub_array, 9, MPI_INT,i, 0, MPI_COMM_WORLD, &status); // root receives the subarrays from each node;
}
if(my_rank != 0)
{
// for the process with rank=1;
for(i=0; i<3 ; i++)
{
MPI_Recv(&(sub_array[i][0]),9,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
for(k=0; k<9 ; k++)
{
for(m=0 ; m<20 ; m++) // here the process with rank=1 calculates the histogram
{
if(sub_array[i][k] == m)
c[m]++;
}
}
}
// for the process with rank=2
for(i=3; i<6 ; i++)
{
MPI_Recv(&(sub_array[i][0]),9,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
for(k=0; k<9 ; k++)
{
for(m=0 ; m<20 ; m++) // here the process with rank=2 calculates the histogram
{
if(sub_array[i][k] == m)
c[m]++;
}
}
}
// for the process with rank=3
for(i=6; i<9 ; i++)
{
MPI_Recv(&(sub_array[i][0]),9,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
for(k=0; k<9 ; k++)
{
for(m=0 ; m<20 ; m++) // here the process with rank=3 calculates the histogram
{
if(sub_array[i][k] == m)
c[m]++;
}
}
}
}
// here the histogram must be printed.
for(k=0; k<20 ; k++)
{
printf("\n");
printf("%2d : ",k);
for(i=0 ; i<c[k] ; i++)
{
printf("=");
}
}
MPI_Finalize();
return 0;
}
我按照你所說的編輯了我的代碼,但它仍然不起作用。謝謝你的方式。 –