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 t = time.time() 35 36 # Initialise the communications exchange with a limit on the number of 37 # channels/processes. 38 39 exchange = MyExchange(limit=limit) 40 41 # Initialise an array - it is stored in the exchange to permit automatic 42 # assignment of values as the data arrives. 43 44 results = exchange.D = [0] * N * N 45 46 # Perform the work. 47 48 print "Calculating..." 49 for i in range(0, N): 50 for j in range(0, N): 51 ch = exchange.create() 52 if ch: 53 try: # Calculation work. 54 55 time.sleep(delay) 56 ch.send((i, j, i * N + j)) 57 58 finally: # Important finalisation. 59 60 pprocess.exit(ch) 61 62 # Wait for the results. 63 64 print "Finishing..." 65 exchange.finish() 66 67 # Show the results. 68 69 for i in range(0, N): 70 for result in results[i*N:i*N+N]: 71 print result, 72 print 73 74 print "Time taken:", time.time() - t 75 76 # vim: tabstop=4 expandtab shiftwidth=4