1.1 --- a/examples/simple.py Sun Jan 14 22:52:54 2007 +0000
1.2 +++ b/examples/simple.py Sun Jan 14 22:53:04 2007 +0000
1.3 @@ -1,43 +1,70 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +A simple example of parallel computation.
1.8 +"""
1.9 +
1.10 import pprocess
1.11 import time
1.12
1.13 -N = 10
1.14 +# Array size and a limit on the number of processes.
1.15 +
1.16 +N = 100
1.17 limit = 10
1.18
1.19 def make_array(n):
1.20 +
1.21 + "Make an 'n' * 'n' array initialised with zeros."
1.22 +
1.23 return [list(x) for x in [(0,) * n] * n]
1.24
1.25 def calculate(ch, i, j):
1.26 +
1.27 + """
1.28 + A time-consuming calculation, using 'ch' to communicate with the parent
1.29 + process, with 'i' and 'j' as operands.
1.30 + """
1.31 +
1.32 time.sleep(1)
1.33 ch.send((i, j, i * N + j))
1.34
1.35 -def wait(exchange, D):
1.36 - print "Processes:", len(exchange.active())
1.37 - while len(exchange.active()) >= limit:
1.38 - store(exchange, D)
1.39 +class MyExchange(pprocess.Exchange):
1.40 +
1.41 + "Parallel convenience class containing the array assignment operation."
1.42
1.43 -def store(exchange, D):
1.44 - for ch in exchange.ready():
1.45 + def store_data(self, ch):
1.46 i, j, result = ch.receive()
1.47 - D[i][j] = result
1.48 + self.D[i][j] = result
1.49 +
1.50 +# Main program.
1.51
1.52 if __name__ == "__main__":
1.53 - D = make_array(N)
1.54 - exchange = pprocess.Exchange()
1.55 +
1.56 + # Initialise the communications exchange with a limit on the number of
1.57 + # channels/processes.
1.58 +
1.59 + exchange = MyExchange(limit=limit)
1.60 +
1.61 + # Initialise an array - it is stored in the exchange to permit automatic
1.62 + # assignment of values as the data arrives.
1.63 +
1.64 + exchange.D = make_array(N)
1.65 +
1.66 + # The parallel computation.
1.67
1.68 print "Calculating..."
1.69 for i in range(0, N):
1.70 for j in range(0, N):
1.71 ch = pprocess.start(calculate, i, j)
1.72 - wait(exchange, D)
1.73 - exchange.add(ch)
1.74 + exchange.add_wait(ch)
1.75
1.76 print "Finishing..."
1.77 - while exchange.active():
1.78 - store(exchange, D)
1.79 + exchange.finish()
1.80 +
1.81 + # Show the result.
1.82
1.83 print
1.84 - for row in D:
1.85 + for row in exchange.D:
1.86 print row
1.87
1.88 # vim: tabstop=4 expandtab shiftwidth=4