[85] | 1 | #!/usr/bin/env python |
---|
| 2 | ######################################################### |
---|
| 3 | # |
---|
| 4 | # Example: Running Python in parallel using pypar (MPI). |
---|
| 5 | # |
---|
| 6 | # Author: Ole Nielsen, SMS, ANU, Jan. 2002. |
---|
| 7 | # |
---|
| 8 | ######################################################### |
---|
| 9 | # |
---|
| 10 | # The purpose of this code is to demonstrate how Python can be |
---|
| 11 | # used to communicate among processes using pypar. |
---|
| 12 | # |
---|
| 13 | # This demo passes messages on in a ring from processor n-1 to n starting |
---|
| 14 | # and ending with processor 0. |
---|
| 15 | # Each processor adds some text to the message before passing it on |
---|
| 16 | # and writes a log statement to the screen. |
---|
| 17 | # |
---|
| 18 | # To execute: |
---|
| 19 | # |
---|
| 20 | # mpirun -np 4 demo.py |
---|
| 21 | |
---|
| 22 | |
---|
| 23 | import pypar # The Python-MPI interface |
---|
| 24 | |
---|
| 25 | numproc = pypar.size() |
---|
| 26 | myid = pypar.rank() |
---|
[123] | 27 | node = pypar.get_processor_name() |
---|
[85] | 28 | |
---|
| 29 | print "I am proc %d of %d on node %s" %(myid, numproc, node) |
---|
| 30 | |
---|
| 31 | |
---|
| 32 | if numproc < 2: |
---|
| 33 | print "Demo must run on at least 2 processors to continue" |
---|
| 34 | pypar.Abort() |
---|
| 35 | |
---|
| 36 | if myid == 0: |
---|
| 37 | msg = "MSGP0" |
---|
| 38 | |
---|
| 39 | print 'Processor 0 sending message "%s" to processor %d' %(msg, 1) |
---|
| 40 | pypar.send(msg, 1) |
---|
| 41 | |
---|
| 42 | msg, status = pypar.receive(numproc-1, return_status=True) |
---|
| 43 | print 'Processor 0 received message "%s" from processor %d' %(msg, numproc-1) |
---|
| 44 | print 'Size of msg was %d bytes' %(status.bytes()) |
---|
| 45 | |
---|
| 46 | else: |
---|
| 47 | source = myid-1 |
---|
| 48 | destination = (myid+1)%numproc |
---|
| 49 | |
---|
| 50 | msg, status = pypar.receive(source, return_status=True) |
---|
| 51 | print 'Processor %d received message "%s" from processor %d'\ |
---|
| 52 | %(myid, msg, source) |
---|
| 53 | print 'Size of msg was %d bytes' %(status.bytes()) |
---|
| 54 | |
---|
| 55 | msg = msg + '->P' + str(myid) #Update message |
---|
| 56 | print 'Processor %d sending msg "%s" to %d' %(myid, msg, destination) |
---|
| 57 | pypar.send(msg, destination) |
---|
| 58 | |
---|
[123] | 59 | pypar.finalize() |
---|
[85] | 60 | |
---|
| 61 | |
---|
| 62 | |
---|