这是我的代码:
int world_size;
MPI_Comm_size(MPI_COMM_WORLD , &world_size);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD , &world_rank);
int *rbuf , arr[world_size];
if (world_rank == 0)
{
rbuf = (int *) malloc(world_size * 1 * sizeof(int));
}
else
{
rbuf[0] = rand() % 100;
MPI_Send(rbuf , 1 , MPI_INT , 0 , 0 , MPI_COMM_WORLD);
}
if (world_rank == 0)
{
MPI_Gather(arr , world_size , MPI_INT , rbuf , 1 , MPI_INT , 0 , MPI_COMM_WORLD);
for (int i = 0; i < world_size; ++i)
{
printf("%d " , arr[i]);
}
printf("\n");
}
我想在不是根进程的每个进程中生成一个随机数。然后,我希望每个这样的进程将生成的数字发送到根进程,即。根进程应收集在每个进程中生成的所有数字。
当我尝试运行此代码时,出现错误:
Fatal error in PMPI_Gather: Message truncated, error stack:
PMPI_Gather(896)......: MPI_Gather(sbuf=0x7ffc3b23c180, scount=10, MPI_INT, rbuf=0x564a753dc790, rcount=1, MPI_INT, root=0, MPI_COMM_WORLD) failed
MPIR_Gather_impl(718).:
MPIR_Gather(678)......:
MPIR_Gather_intra(184):
MPIR_Localcopy(74)....: Message truncated; 40 bytes received but buffer size is 4
(PS。我使用mpirun -n 10 ./helloworld
运行此程序)
答案 0 :(得分:3)
MPI_Gather
从各个级别向根发送消息并接收自身,不需要MPI_Send
。
我更改了您的示例:
#include<stdio.h>
#include<mpi.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char **argv){
MPI_Init(&argc, &argv);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD , &world_size);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD , &world_rank);
srand(time(NULL)+world_rank);
int *rbuf,*sender;
if (world_rank == 0)
{
rbuf = (int *) malloc(world_size * 1 * sizeof(int));
}
sender = (int *) malloc( 1 * sizeof(int));
sender[0] = rand() % 100;
MPI_Gather(sender , 1 , MPI_INT , rbuf , 1 , MPI_INT , 0 , MPI_COMM_WORLD);
if (world_rank == 0)
{
for (int i = 0; i < world_size; ++i)
{
printf("%d " , rbuf[i]);
}
printf("\n");
}
MPI_Finalize();
}