1 #!/usr/bin/env python 2 3 """ 4 A simple example of parallel computation. 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 def make_array(n): 17 18 "Make an 'n' * 'n' array initialised with zeros." 19 20 return [list(x) for x in [(0,) * n] * n] 21 22 def calculate(ch, i, j): 23 24 """ 25 A time-consuming calculation, using 'ch' to communicate with the parent 26 process, with 'i' and 'j' as operands. 27 """ 28 29 time.sleep(delay) 30 ch.send((i, j, i * N + j)) 31 32 class MyExchange(pprocess.Exchange): 33 34 "Parallel convenience class containing the array assignment operation." 35 36 def store_data(self, ch): 37 i, j, result = ch.receive() 38 self.D[i][j] = result 39 40 # Main program. 41 42 if __name__ == "__main__": 43 44 # Initialise the communications exchange with a limit on the number of 45 # channels/processes. 46 47 exchange = MyExchange(limit=limit) 48 49 # Initialise an array - it is stored in the exchange to permit automatic 50 # assignment of values as the data arrives. 51 52 exchange.D = make_array(N) 53 54 # The parallel computation. 55 56 print "Calculating..." 57 for i in range(0, N): 58 for j in range(0, N): 59 exchange.start(calculate, i, j) 60 print i, j 61 62 print "Finishing..." 63 exchange.finish() 64 65 # Show the result. 66 67 print 68 for row in exchange.D: 69 print row 70 71 # vim: tabstop=4 expandtab shiftwidth=4