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