1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <vector>
#include "mpi.h"
using namespace std;
int main( int argc, char* argv[] )
{
int rank, nproc;
MPI_Status stat;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &nproc );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
int root = 0;
vector<double> A;
int n;
if ( rank == root )
{
A = { 10, 20, 30, 40, 50 }; // Only root knows A and n
n = A.size();
}
// ALL processors must make these calls
MPI_Bcast( &n, 1, MPI_INT, root, MPI_COMM_WORLD ); // Send size from root to ALL
A.resize( n ); // Should have no effect on root
MPI_Bcast( A.data(), n, MPI_DOUBLE, root, MPI_COMM_WORLD ); // Send data from root to ALL
for ( int p = 1; p < nproc; p++ )
{
MPI_Barrier( MPI_COMM_WORLD ); // ONLY USE FOR DEBUGGING PURPOSES (like this)
if ( rank == p )
{
cout << "Processor " << rank << " received " << n << " pieces of data: ";
for ( double x : A ) cout << x << " ";
cout << '\n';
}
}
MPI_Finalize();
}
|