paulb@98 | 1 | #!/usr/bin/env python |
paulb@98 | 2 | |
paulb@98 | 3 | """ |
paulb@98 | 4 | A simple example of parallel computation using message queues and the create |
paulb@98 | 5 | function. |
paulb@98 | 6 | """ |
paulb@98 | 7 | |
paulb@98 | 8 | import pprocess |
paulb@98 | 9 | import time |
paulb@98 | 10 | |
paulb@98 | 11 | # Array size and a limit on the number of processes. |
paulb@98 | 12 | |
paulb@98 | 13 | N = 10 |
paulb@98 | 14 | limit = 10 |
paulb@98 | 15 | delay = 1 |
paulb@98 | 16 | |
paulb@98 | 17 | # Main program. |
paulb@98 | 18 | |
paulb@98 | 19 | if __name__ == "__main__": |
paulb@98 | 20 | |
paulb@98 | 21 | # Initialise the communications queue with a limit on the number of |
paulb@98 | 22 | # channels/processes. |
paulb@98 | 23 | |
paulb@98 | 24 | queue = pprocess.Queue(limit=limit) |
paulb@98 | 25 | t = time.time() |
paulb@98 | 26 | |
paulb@98 | 27 | # Initialise an array. |
paulb@98 | 28 | |
paulb@98 | 29 | D = [0] * N * N |
paulb@98 | 30 | |
paulb@98 | 31 | # The parallel computation. |
paulb@98 | 32 | # NOTE: Could use the with statement in the loop to package the |
paulb@98 | 33 | # NOTE: try...finally functionality. |
paulb@98 | 34 | |
paulb@98 | 35 | print "Calculating..." |
paulb@98 | 36 | for i in range(0, N): |
paulb@98 | 37 | for j in range(0, N): |
paulb@98 | 38 | ch = queue.create() |
paulb@98 | 39 | if ch: |
paulb@98 | 40 | try: # Calculation work. |
paulb@98 | 41 | |
paulb@98 | 42 | time.sleep(delay) |
paulb@98 | 43 | ch.send((i, j, i * N + j)) |
paulb@98 | 44 | |
paulb@98 | 45 | finally: # Important finalisation. |
paulb@98 | 46 | |
paulb@98 | 47 | pprocess.exit(ch) |
paulb@98 | 48 | |
paulb@98 | 49 | print "Finishing..." |
paulb@98 | 50 | for i, j, result in queue: |
paulb@98 | 51 | D[i*N+j] = result |
paulb@98 | 52 | |
paulb@98 | 53 | # Show the result. |
paulb@98 | 54 | |
paulb@98 | 55 | print "Time taken:", time.time() - t |
paulb@98 | 56 | for i in range(0, N): |
paulb@98 | 57 | for result in D[i*N:i*N+N]: |
paulb@98 | 58 | print result, |
paulb@98 | 59 | print |
paulb@98 | 60 | |
paulb@98 | 61 | # vim: tabstop=4 expandtab shiftwidth=4 |