How to do it...

In the following example, we will utilize the comm.send and comm.recv directives to exchange messages between different processes:

  1. Import the relevant mpi4py library:
from mpi4py import MPI

  1. Then, we define the communicator parameter, namely comm, through the MPI.COMM_WORLD statement:
comm=MPI.COMM_WORLD 
  1. The rank parameter is used to identify the process itself:
rank = comm.rank 
  1. It is useful to print out the rank of a process:
print("my rank is : " , rank) 
  1. Then, we start considering the rank of the process. In this case, for the process of rank equal to 0, we set destination_process and data (in this case data = 10000000) to be sent:
if rank==0: 
    data= 10000000 
    destination_process = 4 
  1. Then, by using the comm.send statementthe data that was previously set is sent to the destination process:
    comm.send(data,dest=destination_process) 
    print ("sending data %s " %data +   
           "to process %d" %destination_process) 
  1. For the process of rank equal to 1, the destination_process value is 8, while the data to be sent is the "hello" string:
if rank==1: 
    destination_process = 8 
    data= "hello" 
    comm.send(data,dest=destination_process) 
    print ("sending data %s :" %data +   
           "to process %d" %destination_process) 
  1. The process of rank equal to 4 is a receiver process. Indeed, the source process (that is, the process of rank equal to 0) is set as a parameter in the comm.recv statement:
if rank==4: 
    data=comm.recv(source=0) 

  1. Now, using the following code, the data received from the process of 0 must be displayed:
    print ("data received is = %s" %data) 
  1. The last process to be set is number 9. Here, we define the source process of rank equal to 1 as a parameter in the comm.recv statement:
if rank==8: 
    data1=comm.recv(source=1) 
  1. The data1 value is then printed:
 print ("data1 received is = %s" %data1) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.51.117