1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/simple_create.py Sat Sep 15 00:12:05 2007 +0000
1.3 @@ -0,0 +1,71 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +A simple example of parallel computation using message exchanges 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 +# Monitoring class.
1.21 +
1.22 +class MyExchange(pprocess.Exchange):
1.23 +
1.24 + "Parallel convenience class containing the array assignment operation."
1.25 +
1.26 + def store_data(self, ch):
1.27 + i, j, result = ch.receive()
1.28 + self.D[i*N+j] = result
1.29 +
1.30 +# Main program.
1.31 +
1.32 +if __name__ == "__main__":
1.33 +
1.34 + # Initialise the communications exchange with a limit on the number of
1.35 + # channels/processes.
1.36 +
1.37 + exchange = MyExchange(limit=limit)
1.38 + t = time.time()
1.39 +
1.40 + # Initialise an array - it is stored in the exchange to permit automatic
1.41 + # assignment of values as the data arrives.
1.42 +
1.43 + exchange.D = [0] * N * N
1.44 +
1.45 + # The parallel computation.
1.46 + # NOTE: Could use the with statement in the loop to package the
1.47 + # NOTE: try...finally functionality.
1.48 +
1.49 + print "Calculating..."
1.50 + for i in range(0, N):
1.51 + for j in range(0, N):
1.52 + ch = exchange.create()
1.53 + if ch:
1.54 + try: # Calculation work.
1.55 +
1.56 + time.sleep(delay)
1.57 + ch.send((i, j, i * N + j))
1.58 +
1.59 + finally: # Important finalisation.
1.60 +
1.61 + pprocess.exit(ch)
1.62 +
1.63 + print "Finishing..."
1.64 + exchange.finish()
1.65 +
1.66 + # Show the result.
1.67 +
1.68 + print "Time taken:", time.time() - t
1.69 + for i in range(0, N):
1.70 + for result in exchange.D[i*N:i*N+N]:
1.71 + print result,
1.72 + print
1.73 +
1.74 +# vim: tabstop=4 expandtab shiftwidth=4