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