版权声明:博主原创文章属私人所有,未经允许 不可转发和使用 https://blog.csdn.net/a1066196847/article/details/89682676
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <mpi.h>
using namespace std;
void my_bcast(void* data, int count, MPI_Datatype datatype, int root,
MPI_Comm communicator) {
int world_rank;
MPI_Comm_rank(communicator, &world_rank);
int world_size;
MPI_Comm_size(communicator, &world_size);
if (world_rank == root) {
// If we are the root process, send our data to everyone
int i;
for (i = 0; i < world_size; i++) {
if (i != world_rank) {
MPI_Send(data, count, datatype, i, 0, communicator);
}
}
cout << "Process " << world_rank << " broadcasting data " << data << endl;
} else {
// If we are a receiver process, receive the data from the root
MPI_Recv(data, count, datatype, root, 0, communicator,
MPI_STATUS_IGNORE);
cout << "Process " << world_rank << " received data " << data << " from root process " << endl;
}
}
int main(int argc, char** argv) {
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int data = 100;
my_bcast(&data, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
这个程序很容易理解
mpicxx main.cpp -o main.out
mpirun -np 5 ./main.out
输出为:
Process 0 broadcasting data 0x7fff5225c7c4
Process 1 received data 0x7ffe888c6804 from root process
Process 2 received data 0x7ffddffaa6b4 from root process
Process 3 received data 0x7ffc4ab036d4 from root process
Process 4 received data 0x7ffd4bf7fa34 from root process