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