1 #!/usr/bin/env python 2 3 """ 4 A simple example of parallel computation using a queue and the start method. 5 """ 6 7 import pprocess 8 import time 9 10 # Array size and a limit on the number of processes. 11 12 N = 10 13 limit = 10 14 delay = 1 15 16 # Work function. 17 18 def calculate(i, j): 19 20 "A supposedly time-consuming calculation on 'i' and 'j'." 21 22 time.sleep(delay) 23 return (i, j, i * N + j) 24 25 # Main program. 26 27 if __name__ == "__main__": 28 29 # Initialise the communications queue with a limit on the number of 30 # channels/processes. 31 32 queue = pprocess.Queue(limit=limit) 33 t = time.time() 34 35 # Initialise an array. 36 37 results = [0] * N * N 38 39 # Wrap the calculate function. 40 41 calc = pprocess.MakeParallel(calculate) 42 43 # Perform the work. 44 45 for i in range(0, N): 46 for j in range(0, N): 47 queue.start(calc, *(i, j)) 48 49 # Store the results as they arrive. 50 51 print "Finishing..." 52 for i, j, result in queue: 53 results[i*N+j] = result 54 55 # Show the results. 56 57 print "Time taken:", time.time() - t 58 for i in range(0, N): 59 for result in results[i*N:i*N+N]: 60 print result, 61 print 62 63 # vim: tabstop=4 expandtab shiftwidth=4