1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/simple_queue.py Sat Sep 15 00:12:05 2007 +0000
1.3 @@ -0,0 +1,61 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +A simple example of parallel computation using message queues and the create
1.8 +function.
1.9 +"""
1.10 +
1.11 +import pprocess
1.12 +import time
1.13 +
1.14 +# Array size and a limit on the number of processes.
1.15 +
1.16 +N = 10
1.17 +limit = 10
1.18 +delay = 1
1.19 +
1.20 +# Main program.
1.21 +
1.22 +if __name__ == "__main__":
1.23 +
1.24 + # Initialise the communications queue with a limit on the number of
1.25 + # channels/processes.
1.26 +
1.27 + queue = pprocess.Queue(limit=limit)
1.28 + t = time.time()
1.29 +
1.30 + # Initialise an array.
1.31 +
1.32 + D = [0] * N * N
1.33 +
1.34 + # The parallel computation.
1.35 + # NOTE: Could use the with statement in the loop to package the
1.36 + # NOTE: try...finally functionality.
1.37 +
1.38 + print "Calculating..."
1.39 + for i in range(0, N):
1.40 + for j in range(0, N):
1.41 + ch = queue.create()
1.42 + if ch:
1.43 + try: # Calculation work.
1.44 +
1.45 + time.sleep(delay)
1.46 + ch.send((i, j, i * N + j))
1.47 +
1.48 + finally: # Important finalisation.
1.49 +
1.50 + pprocess.exit(ch)
1.51 +
1.52 + print "Finishing..."
1.53 + for i, j, result in queue:
1.54 + D[i*N+j] = result
1.55 +
1.56 + # Show the result.
1.57 +
1.58 + print "Time taken:", time.time() - t
1.59 + for i in range(0, N):
1.60 + for result in D[i*N:i*N+N]:
1.61 + print result,
1.62 + print
1.63 +
1.64 +# vim: tabstop=4 expandtab shiftwidth=4