Let's now see an example in which we've used the broadcast function. We have a root process of rank equal to 0 that shares its own data, variable_to_share, with the other processes defined in the communicator group:
- Let's import the mpi4py library:
from mpi4py import MPI
- Now, let's define the communicator and the rank parameter:
comm = MPI.COMM_WORLD rank = comm.Get_rank()
- As far as the process of rank equal to 0 is concerned, we define the variable to be shared among the other processes:
if rank == 0: variable_to_share = 100 else: variable_to_share = None
- Finally, we define a broadcast, having the rank process equal to zero as its root:
variable_to_share = comm.bcast(variable_to_share, root=0) print("process = %d" %rank + " variable shared = %d " %variable_to_share)