Message Passing Interface (MPI) : MPI_Bcast example

by

in


This post talks about a MPI Broadcast function – MPI_Bcast. Broadcast operation is used to send data from one process to all other processes within a communicator. Every process receives the same data.

Syntax for MPI_Bcast

int MPI_Bcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm)

Input Parameters

  • count : number of elements/values to be Broadcasted (for example : 0)
  • datatype : data type of elements/values to be sent (for example : 10)
  • root : rank of root process (for example : 0)
  • comm : communicator (for example : MPI_COMM_WORLD)

Input/Output Parameters

  • buffer : Pointer to the data/array to be sent/received (for example : int *myarr)

Example code –

#include"stdio.h"
#include"mpi.h"

int main(int argc, char **argv)
{
	int myid, size;
	int data;
	
	//Initialize MPI environment 
	MPI_Init(&argc,&argv);
	
	//Get total number of processes
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	
	//Get my unique identification among all processes
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	
	//Initialize data to some value
	data = 20;
	
	//If root
	if(myid==0)
	{
		data = 10;			
	}
	//Bradcast the data
	MPI_Bcast(&data, 1, MPI_INT, 0, MPI_COMM_WORLD);
	
	//Every process prints the value of data
	printf("myid:%d \t data = %d\n",myid, data);
	
	//End MPI environment        
	MPI_Finalize();
}


To compile this code, use following command –

mpicc mpi_broadcast.c


To execute this code, run following command –

mpiexec -n 4 ./a.out


Output of this code will be something similar to the following –

myid:0 	 data = 10
myid:1 	 data = 10
myid:2 	 data = 10
myid:3 	 data = 10

To know more about MPI, visit our dedicated page for MPI here.

If you are new to Parallel Programming / HPC, visit our dedicated page for beginners.

References


Mandar Gurav Avatar

Mandar Gurav

Parallel Programmer, Trainer and Mentor


If you are new to Parallel Programming you can start here.



Beginner CUDA Fortran Hello World Message Passing Interface MPI Nvidia Nsight Systems NVPROF OpenACC OpenACC Fortran OpenMP PGI Fortran Compiler Profiling Vector Addition


Popular Categories