File: simple_create.py

package info (click to toggle)
pprocess 0.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 404 kB
  • ctags: 440
  • sloc: python: 2,048; makefile: 106; sh: 41
file content (78 lines) | stat: -rw-r--r-- 1,699 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python

"""
A simple example of parallel computation using message exchanges and the create
function.

NOTE: We could use the with statement in the innermost loop to package the
NOTE: try...finally functionality.
"""

import pprocess
import time
#import random

# Array size and a limit on the number of processes.

N = 10
limit = 10
delay = 1

# Monitoring class.

class MyExchange(pprocess.Exchange):

    "Parallel convenience class containing the array assignment operation."

    def store_data(self, ch):
        i, j, result = ch.receive()
        self.D[i*N+j] = result

# Main program.

if __name__ == "__main__":

    t = time.time()

    # 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.

    results = exchange.D = [0] * N * N

    # Perform the work.

    print "Calculating..."
    for i in range(0, N):
        for j in range(0, N):
            ch = exchange.create()
            if ch:
                try: # Calculation work.

                    #time.sleep(delay * random.random())
                    time.sleep(delay)
                    ch.send((i, j, i * N + j))

                finally: # Important finalisation.

                    pprocess.exit(ch)

    # Wait for the results.

    print "Finishing..."
    exchange.finish()

    # Show the results.

    for i in range(0, N):
        for result in results[i*N:i*N+N]:
            print result,
        print

    print "Time taken:", time.time() - t

# vim: tabstop=4 expandtab shiftwidth=4