我是MPI的新手,并尝试学习如何在函数中使用MPI_Bcast和MPI_Gather。如果我按照以下方式不使用函数编写代码,它可以正常工作并给出正确的结果:
结束时打印结果:
localdata [0]:19,localdata [1]:19,localdata [2]:20,localdata [3]:20,localdata [4]:21,localdata [5]:21,localdata [6]:22,localdata [7]:22,
要使用4个处理器进行编译和运行,请使用以下命令:
:$ mpicc test.c -o test
:$ mpirun -np 4 test
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int i, total;
int arr[20];
int localdata[8];
if (world_rank == 0)
{
for(i=0;i<20;i++)
arr[i]=i;
MPI_Bcast( &arr, 20, MPI_INT, 0, MPI_COMM_WORLD );
printf("\n\n* At Process %d received\n", world_rank);
for(i=0;i<20;i++)
{
printf("ARR[%d]:%d, ",i, arr[i]);
total=arr[i]+world_rank;
}
printf("\n");
localdata[0]=total;
localdata[1]=total;
MPI_Gather(localdata, 2, MPI_INT, localdata, 2, MPI_INT,0, MPI_COMM_WORLD);
printf("\n\nPrinting Result at the end:\n");
for(i=0;i<8;i++)
{
printf("localdata[%d]:%d, ",i, localdata[i]);
}
printf("\n\n");
}
else
{
MPI_Bcast( &arr, 20, MPI_INT, 0, MPI_COMM_WORLD );
printf("\n\n* At Process %d received\n", world_rank);
for(i=0;i<20;i++)
{
printf("ARR[%d]:%d, ",i, arr[i]);
total=arr[i]+world_rank;
}
printf("\n");
localdata[0]=total;
localdata[1]=total;
MPI_Gather(localdata, 2, MPI_INT, localdata, 2, MPI_INT,0, MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}
当我将这些代码放在一个名为function_cal
的函数中时,它会给我以下错误:
*** Process received signal ***
Signal: Segmentation fault (11)
Signal code: Address not mapped (1)
Failing at address: 0x7fffdeb18040
以下是将MPI_Bcast和MPI_Gather放入函数后的代码。任何帮助将不胜感激。
#include <mpi.h>
#include <stdio.h>
void function_cal(int arr[20], int localdata[8], int world_rank)
{
int i, total;
MPI_Bcast( &arr, 20, MPI_INT, 0, MPI_COMM_WORLD );
printf("\n\n* At Process %d received\n", world_rank);
for(i=0;i<20;i++)
{
printf("ARR[%d]:%d, ",i, arr[i]);
total=arr[i]+world_rank;
}
printf("\n");
localdata[0]=total;
localdata[1]=total;
MPI_Gather(localdata, 2, MPI_INT, localdata, 2, MPI_INT,0, MPI_COMM_WORLD);
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int i;
int arr[20];
int localdata[8];
if (world_rank == 0)
{
for(i=0;i<20;i++)
arr[i]=i;
function_cal(arr, localdata, world_rank);
printf("\n\nPrinting Result at the end:\n");
for(i=0;i<8;i++)
{
printf("localdata[%d]:%d, ",i, localdata[i]);
}
printf("\n\n");
}
else
{
function_cal(arr, localdata, world_rank);
}
MPI_Finalize();
return 0;
}