lots
[arrocco.git] / spawn / __init__.py
blob2bb8edeac356c9cc0100c6b90a26a33b13c230f8
1 # __init__.py
2 # 14 Aug 2007
4 import time, thread, weakref, gc
6 class Process:
7 def __init__(self, computation, stopper):
8 self.container = [None]
9 self.computation = computation
10 self.stopper = stopper
12 def run(self):
13 try:
14 self.container[0] = self.computation()
15 except Exception, e:
16 self.container[0] = repr(e)
18 class MyList(list):
19 def __init__(self, x):
20 list.__init__(self)
21 self.append(x)
23 class MyObject: pass
25 def spawn(computation, stopper):
26 proc = Process(computation, stopper)
28 token = MyObject()
29 wref = weakref.ref(token, lambda arg: stopper())
31 class Retriever:
32 def __init__(self):
33 self.children = []
35 def __call__(self):
36 x = proc.container[0]
37 if x is None: return ('working', None)
38 else: return ('done', x)
40 def __repr__(self):
41 return '<Retriever holding value %s>' % str(self())
43 def stop(self):
44 stopper()
45 for kid in self.children:
46 kid.stop()
48 def spawn(self, comp, stopr):
49 p = globals().spawn(comp, stopr)
50 self.children.append(p)
52 def start(self):
53 thread.start_new_thread(proc.run, ())
55 r = Retriever()
56 r.saving_ref = token
57 del token
58 return r
60 def fib(n, go):
61 if not go[0]:
62 raise Exception, "Cancelled"
63 elif n <= 2:
64 return 1
65 else:
66 return fib(n - 1, go) + fib(n - 2, go)
68 def test(n):
69 go = [True]
70 def stop(): go[0] = False
71 return spawn(lambda: fib(n, go), stop)