1 #!/usr/bin/env python 2 3 """ 4 A simple example of parallel computation using message exchanges and the create 5 function. 6 7 NOTE: We could use the with statement in the innermost loop to package the 8 NOTE: try...finally functionality. 9 """ 10 11 import pprocess 12 import time 13 14 # Array size and a limit on the number of processes. 15 16 N = 10 17 limit = 10 18 delay = 1 19 20 # Monitoring class. 21 22 class MyExchange(pprocess.Exchange): 23 24 "Parallel convenience class containing the array assignment operation." 25 26 def store_data(self, ch): 27 i, j, result = ch.receive() 28 self.D[i*N+j] = result 29 30 # Main program. 31 32 if __name__ == "__main__": 33 34 # Initialise the communications exchange with a limit on the number of 35 # channels/processes. 36 37 exchange = MyExchange(limit=limit) 38 t = time.time() 39 40 # Initialise an array - it is stored in the exchange to permit automatic 41 # assignment of values as the data arrives. 42 43 exchange.D = [0] * N * N 44 45 # Perform the work. 46 47 print "Calculating..." 48 for i in range(0, N): 49 for j in range(0, N): 50 ch = exchange.create() 51 if ch: 52 try: # Calculation work. 53 54 time.sleep(delay) 55 ch.send((i, j, i * N + j)) 56 57 finally: # Important finalisation. 58 59 pprocess.exit(ch) 60 61 # Wait for the results. 62 63 print "Finishing..." 64 exchange.finish() 65 66 # Show the results. 67 68 print "Time taken:", time.time() - t 69 for i in range(0, N): 70 for result in exchange.D[i*N:i*N+N]: 71 print result, 72 print 73 74 # vim: tabstop=4 expandtab shiftwidth=4