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