1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/simple_managed.py Fri Sep 14 23:16:24 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 exchanges and managed callables.
1.8 +"""
1.9 +
1.10 +import pprocess
1.11 +import time
1.12 +
1.13 +# Array size and a limit on the number of processes.
1.14 +
1.15 +N = 10
1.16 +limit = 10
1.17 +delay = 1
1.18 +
1.19 +# Work function and monitoring class.
1.20 +
1.21 +def calculate(ch, i, j):
1.22 +
1.23 + """
1.24 + A time-consuming calculation, using 'ch' to communicate with the parent
1.25 + process, with 'i' and 'j' as operands.
1.26 + """
1.27 +
1.28 + time.sleep(delay)
1.29 + ch.send((i, j, i * N + j))
1.30 +
1.31 +class MyExchange(pprocess.Exchange):
1.32 +
1.33 + "Parallel convenience class containing the array assignment operation."
1.34 +
1.35 + def store_data(self, ch):
1.36 + i, j, result = ch.receive()
1.37 + self.D[i*N+j] = result
1.38 +
1.39 +# Main program.
1.40 +
1.41 +if __name__ == "__main__":
1.42 +
1.43 + # Initialise the communications exchange with a limit on the number of
1.44 + # channels/processes.
1.45 +
1.46 + exchange = MyExchange(limit=limit)
1.47 + t = time.time()
1.48 +
1.49 + # Initialise an array - it is stored in the exchange to permit automatic
1.50 + # assignment of values as the data arrives.
1.51 +
1.52 + exchange.D = [0] * N * N
1.53 + calc = exchange.manage(calculate)
1.54 +
1.55 + print "Calculating..."
1.56 + for i in range(0, N):
1.57 + for j in range(0, N):
1.58 + calc(i, j)
1.59 +
1.60 + print "Finishing..."
1.61 + exchange.finish()
1.62 +
1.63 + print "Time taken:", time.time() - t
1.64 + for i in range(0, N):
1.65 + for result in exchange.D[i*N:i*N+N]:
1.66 + print result,
1.67 + print
1.68 +
1.69 +# vim: tabstop=4 expandtab shiftwidth=4