1 #!/usr/bin/env python 2 3 """ 4 A simple example of parallel computation using message queues 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 # Main program. 21 22 if __name__ == "__main__": 23 24 t = time.time() 25 26 # Initialise the communications queue with a limit on the number of 27 # channels/processes. 28 29 queue = pprocess.Queue(limit=limit) 30 31 # Initialise an array. 32 33 results = [0] * N * N 34 35 # Perform the work. 36 # NOTE: Could use the with statement in the loop to package the 37 # NOTE: try...finally functionality. 38 39 print "Calculating..." 40 for i in range(0, N): 41 for j in range(0, N): 42 ch = queue.create() 43 if ch: 44 try: # Calculation work. 45 46 time.sleep(delay) 47 ch.send((i, j, i * N + j)) 48 49 finally: # Important finalisation. 50 51 pprocess.exit(ch) 52 53 # Store the results as they arrive. 54 55 print "Finishing..." 56 for i, j, result in queue: 57 results[i*N+j] = result 58 59 # Show the results. 60 61 for i in range(0, N): 62 for result in results[i*N:i*N+N]: 63 print result, 64 print 65 66 print "Time taken:", time.time() - t 67 68 # vim: tabstop=4 expandtab shiftwidth=4