1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/simple_create_queue.py Sat Sep 15 15:57:34 2007 +0000
1.3 @@ -0,0 +1,66 @@
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 +NOTE: We could use the with statement in the innermost loop to package the
1.11 +NOTE: try...finally functionality.
1.12 +"""
1.13 +
1.14 +import pprocess
1.15 +import time
1.16 +
1.17 +# Array size and a limit on the number of processes.
1.18 +
1.19 +N = 10
1.20 +limit = 10
1.21 +delay = 1
1.22 +
1.23 +# Main program.
1.24 +
1.25 +if __name__ == "__main__":
1.26 +
1.27 + # Initialise the communications queue with a limit on the number of
1.28 + # channels/processes.
1.29 +
1.30 + queue = pprocess.Queue(limit=limit)
1.31 + t = time.time()
1.32 +
1.33 + # Initialise an array.
1.34 +
1.35 + D = [0] * N * N
1.36 +
1.37 + # Perform the work.
1.38 + # NOTE: Could use the with statement in the loop to package the
1.39 + # NOTE: try...finally functionality.
1.40 +
1.41 + print "Calculating..."
1.42 + for i in range(0, N):
1.43 + for j in range(0, N):
1.44 + ch = queue.create()
1.45 + if ch:
1.46 + try: # Calculation work.
1.47 +
1.48 + time.sleep(delay)
1.49 + ch.send((i, j, i * N + j))
1.50 +
1.51 + finally: # Important finalisation.
1.52 +
1.53 + pprocess.exit(ch)
1.54 +
1.55 + # Store the results as they arrive.
1.56 +
1.57 + print "Finishing..."
1.58 + for i, j, result in queue:
1.59 + D[i*N+j] = result
1.60 +
1.61 + # Show the results.
1.62 +
1.63 + print "Time taken:", time.time() - t
1.64 + for i in range(0, N):
1.65 + for result in D[i*N:i*N+N]:
1.66 + print result,
1.67 + print
1.68 +
1.69 +# vim: tabstop=4 expandtab shiftwidth=4