#include <mpi.h>
#include<stdio.h>
#include <unistd.h>
int main(int argc, char** argv) {
MPI_Init( &argc, &argv );
int rank;
int size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // 获取当前进程的rank
MPI_Comm_size(MPI_COMM_WORLD, &size); // 获取总进程数
int data[size];
for (int i = 0; i < size; ++i) {
data[i] = i;
}
int root = 0;
// 广播数据
MPI_Bcast(data, size, MPI_INT, root, MPI_COMM_WORLD);
// 在接收广播数据后,每个进程打印接收到的数据
for (int i = 0; i < size; ++i) {
printf( "Process %d received data:%d \n" ,i+1,data[i]);
}
int local_data[size];
for (int i = 0; i < size; ++i) {
local_data[i] = i + rank;
}
// 收集数据到root进程
int global_data[size];
MPI_Gather(local_data, size, MPI_INT, global_data, size, MPI_INT, root, MPI_COMM_WORLD);
// root进程打印收集到的数据
if (rank == root) {
for (int i = 0; i < size * size; ++i) {
printf( "Global data:%d ", global_data[i] );
}
}
MPI_Finalize();
return 0;
}