1 #!/usr/bin/env python 2 3 """ 4 A simple example of parallel computation using message queues and the create 5 function. 6 """ 7 8 import pprocess 9 import time 10 11 # Array size and a limit on the number of processes. 12 13 N = 10 14 limit = 10 15 delay = 1 16 17 # Main program. 18 19 if __name__ == "__main__": 20 21 # Initialise the communications queue with a limit on the number of 22 # channels/processes. 23 24 queue = pprocess.Queue(limit=limit) 25 t = time.time() 26 27 # Initialise an array. 28 29 D = [0] * N * N 30 31 # The parallel computation. 32 # NOTE: Could use the with statement in the loop to package the 33 # NOTE: try...finally functionality. 34 35 print "Calculating..." 36 for i in range(0, N): 37 for j in range(0, N): 38 ch = queue.create() 39 if ch: 40 try: # Calculation work. 41 42 time.sleep(delay) 43 ch.send((i, j, i * N + j)) 44 45 finally: # Important finalisation. 46 47 pprocess.exit(ch) 48 49 print "Finishing..." 50 for i, j, result in queue: 51 D[i*N+j] = result 52 53 # Show the result. 54 55 print "Time taken:", time.time() - t 56 for i in range(0, N): 57 for result in D[i*N:i*N+N]: 58 print result, 59 print 60 61 # vim: tabstop=4 expandtab shiftwidth=4