正如标题所暗示的那样,我希望获取整个2D数组并将整个数组分散到其他进程中。这是我正在使用的代码:
int main(int argc, char **argv)
{
MPI_Init(&argc,&argv);
int i,j,size,rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (argc!=3)
{
printf("Usage : pairwise numberOfSequences lengthOfSequences\n eg. pairwise 10000 50\n");
exit(0);
}
sscanf(argv[1],"%d",&N);
sscanf(argv[2],"%d",&M);
char strings[N][M+1];
if(rank == 0)
{
for (i=0; i<N; i++)
{
//Here I read from a file into the array strings and this works
scanf("%s\n",strings[i]);
printf("Rank:%d i value:%d # %s\n",rank,i,strings[i]);
}
}
MPI_Barrier(MPI_COMM_WORLD);
char array_for_all[N][M+1];
//I think here my parameters are wrong for Scatter.
MPI_Scatter(strings, N*(M+1),MPI_CHAR,array_for_all, N*(M+1), MPI_CHAR, 0,MPI_COMM_WORLD);
for (i=0; i<N; i++)
{
printf("Rank:%d i value:%d # %s\n",rank,i,array_for_all[i]);
}
我不确定我是否正确实现了分散。我不想将数组的一部分发送到每个进程,我想将整个数组发送到每个进程,还是有更好的方法来做到这一点?
答案 0 :(得分:0)
正如@Wesley所示,正确的方法是使用MPI_Bcast()
来广播所有进程中的数据。第一个参数应该是指向数据的指针:&strings[0][0]
。
#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
MPI_Init(&argc,&argv);
int N,M;
int i,j,size,rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (argc!=3)
{
printf("Usage : pairwise numberOfSequences lengthOfSequences\n eg. pairwise 10000 50\n");
exit(0);
}
sscanf(argv[1],"%d",&N);
sscanf(argv[2],"%d",&M);
char strings[N][M+1];
if(rank == 0)
{
for (i=0; i<N; i++)
{
//Here I read from a file into the array strings and this works
scanf("%s",strings[i]);
printf("Rank:%d i value:%d # %s\n",rank,i,strings[i]);fflush(stdout);
}
printf("input over, now output :\n");fflush(stdout);
}
//I think here my parameters are wrong for Scatter.
MPI_Bcast(&strings[0][0],N*(M+1), MPI_CHAR, 0,MPI_COMM_WORLD);
// MPI_Scatter(strings, N*(M+1),MPI_CHAR,array_for_all, N*(M+1), MPI_CHAR, 0,MPI_COMM_WORLD);
for (i=0; i<N; i++)
{
printf("Rank:%d i value:%d # %s\n",rank,i,strings[i]);fflush(stdout);
}
MPI_Finalize();
return 0;
}