# HG changeset patch # User paulb # Date 1184540969 0 # Node ID 93872f29ad5147ca6ac77131056f880f13ead03e # Parent 2b9b685985afaecbe26d1a8266fe78c9383d91df [project @ 2007-07-15 23:09:29 by paulb] Extended the example to show managed callables and map-style processing. diff -r 2b9b685985af -r 93872f29ad51 examples/simple.py --- a/examples/simple.py Sun Jul 15 23:09:04 2007 +0000 +++ b/examples/simple.py Sun Jul 15 23:09:29 2007 +0000 @@ -1,7 +1,9 @@ #!/usr/bin/env python """ -A simple example of parallel computation. +A simple example of parallel computation using message exchanges directly, +exchanges and managed callables, and map-style processing with parallel-enabled +functions. """ import pprocess @@ -19,6 +21,8 @@ return [list(x) for x in [(0,) * n] * n] +# Work function and monitoring class. + def calculate(ch, i, j): """ @@ -37,6 +41,23 @@ i, j, result = ch.receive() self.D[i][j] = result +# Alternative work function. + +def calculate_seq(i, j): + + """ + A version of 'calculate' with a simpler result suitable for sequential + collection. It accepts no channel, pretending to be a function used in a + non-parallel context. + """ + + time.sleep(delay) + return i * N + j + +# The alternative work function converted into a parallel-enabled version. + +calculate2 = pprocess.MakeParallel(calculate_seq) + # Main program. if __name__ == "__main__": @@ -68,4 +89,39 @@ for row in exchange.D: print row + # Try again with managed callables. + + exchange.D = make_array(N) + calc = exchange.manage(calculate) + + print "Calculating..." + for i in range(0, N): + for j in range(0, N): + calc(i, j) + print i, j + + print "Finishing..." + exchange.finish() + + print + for row in exchange.D: + print row + + # Try again with a map, building the results sequentially. + + mymap = pprocess.pmap + results = [] + + print "Calculating..." + for i in range(0, N): + sequence = [] + for j in range(0, N): + sequence.append((i, j)) + results.append(mymap(calculate2, sequence)) + print i + + print + for row in results: + print row + # vim: tabstop=4 expandtab shiftwidth=4