# HG changeset patch # User paulb # Date 1168815184 0 # Node ID 49367c7fd1043dd132e74e19e469edd984263926 # Parent 737f61472592824ed6b817ea21f89f7fba9de31f [project @ 2007-01-14 22:53:04 by paulb] Added a simple example of parallel computation. diff -r 737f61472592 -r 49367c7fd104 examples/simple.py --- a/examples/simple.py Sun Jan 14 22:52:54 2007 +0000 +++ b/examples/simple.py Sun Jan 14 22:53:04 2007 +0000 @@ -1,43 +1,70 @@ +#!/usr/bin/env python + +""" +A simple example of parallel computation. +""" + import pprocess import time -N = 10 +# Array size and a limit on the number of processes. + +N = 100 limit = 10 def make_array(n): + + "Make an 'n' * 'n' array initialised with zeros." + return [list(x) for x in [(0,) * n] * n] def calculate(ch, i, j): + + """ + A time-consuming calculation, using 'ch' to communicate with the parent + process, with 'i' and 'j' as operands. + """ + time.sleep(1) ch.send((i, j, i * N + j)) -def wait(exchange, D): - print "Processes:", len(exchange.active()) - while len(exchange.active()) >= limit: - store(exchange, D) +class MyExchange(pprocess.Exchange): + + "Parallel convenience class containing the array assignment operation." -def store(exchange, D): - for ch in exchange.ready(): + def store_data(self, ch): i, j, result = ch.receive() - D[i][j] = result + self.D[i][j] = result + +# Main program. if __name__ == "__main__": - D = make_array(N) - exchange = pprocess.Exchange() + + # Initialise the communications exchange with a limit on the number of + # channels/processes. + + exchange = MyExchange(limit=limit) + + # Initialise an array - it is stored in the exchange to permit automatic + # assignment of values as the data arrives. + + exchange.D = make_array(N) + + # The parallel computation. print "Calculating..." for i in range(0, N): for j in range(0, N): ch = pprocess.start(calculate, i, j) - wait(exchange, D) - exchange.add(ch) + exchange.add_wait(ch) print "Finishing..." - while exchange.active(): - store(exchange, D) + exchange.finish() + + # Show the result. print - for row in D: + for row in exchange.D: print row # vim: tabstop=4 expandtab shiftwidth=4