7.9. A simple MPI-2 example using two independent programs

The sources main0.py and main1.py show how to use the MPI-2 commands:

These commands allow two separate MPI jobs to connect to each other. These examples are designed to be run interactively. Start one copy of each application in its own window. The >main1.py program will write a port_name string to the terminal, something like:

port= tag#0$port#54838$description#192.31.21.33$ifname#192.31.21.33$

The other program, main0.py, takes this string as input. It will prompt using:

port_name>

Copy the string from the first window to the second inclosing it in quotes. After the two programs connect they send messages to each other and quit.

Example 7-5. main0.py

#!/usr/bin/env python
import numpy
from numpy import *
import mpi
import sys
from time import sleep

sys.argv =  mpi.mpi_init(len(sys.argv),sys.argv)
myid=mpi.mpi_comm_rank(mpi.MPI_COMM_WORLD)
numprocs=mpi.mpi_comm_size(mpi.MPI_COMM_WORLD)

print "hello from python main0   myid= ",myid

port_name=input("port_name>")
print "port=",port_name
server=mpi.mpi_comm_connect(port_name,mpi.MPI_INFO_NULL,0,mpi.MPI_COMM_WORLD)

back=array([100],"i")
mpi.mpi_send(back,1,mpi.MPI_INT,0,5678,server)
back=mpi.mpi_recv(1,mpi.MPI_INT,0,1234,server)
print "got back=",back

sleep(10)
mpi.mpi_comm_disconnect(server);
mpi.mpi_finalize()

Example 7-6. main1.py

#!/usr/bin/env python
import numpy
from numpy import *
import mpi
import sys
from time import sleep

sys.argv =  mpi.mpi_init(len(sys.argv),sys.argv)
myid=mpi.mpi_comm_rank(mpi.MPI_COMM_WORLD)
numprocs=mpi.mpi_comm_size(mpi.MPI_COMM_WORLD)

print "hello from python main1   myid= ",myid

port_name=mpi.mpi_open_port(mpi.MPI_INFO_NULL);
print "port=",port_name
client=mpi.mpi_comm_accept(port_name,mpi.MPI_INFO_NULL,0,mpi.MPI_COMM_WORLD)

back=mpi.mpi_recv(1,mpi.MPI_INT,0,5678,client)
print "back=",back
back[0]=back[0]+1
mpi.mpi_send(back,1,mpi.MPI_INT,0,1234,client)

sleep(10)
mpi.mpi_close_port(port_name);
mpi.mpi_comm_disconnect(client);
mpi.mpi_finalize()