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