diff options
-rw-r--r-- | Demo/threads/Generator.py | 14 |
1 files changed, 11 insertions, 3 deletions
diff --git a/Demo/threads/Generator.py b/Demo/threads/Generator.py index a2713af..2e814a0 100644 --- a/Demo/threads/Generator.py +++ b/Demo/threads/Generator.py @@ -1,8 +1,10 @@ # Generator implementation using threads +import sys import thread -Killed = 'Generator.Killed' +class Killed(Exception): + pass class Generator: # Constructor @@ -16,6 +18,7 @@ class Generator: self.done = 0 self.killed = 0 thread.start_new_thread(self._start, ()) + # Internal routine def _start(self): try: @@ -29,6 +32,7 @@ class Generator: if not self.killed: self.done = 1 self.getlock.release() + # Called by producer for each value; raise Killed if no more needed def put(self, value): if self.killed: @@ -38,6 +42,7 @@ class Generator: self.putlock.acquire() # Wait for next get() call if self.killed: raise Killed + # Called by producer to get next value; raise EOFError if no more def get(self): if self.killed: @@ -47,12 +52,14 @@ class Generator: if self.done: raise EOFError # Say there are no more values return self.value + # Called by consumer if no more values wanted def kill(self): if self.killed: raise TypeError, 'kill() called on killed generator' self.killed = 1 self.putlock.release() + # Clone constructor def clone(self): return Generator(self.func, self.args) @@ -64,11 +71,11 @@ def pi(g): p, q, k = k*k, 2L*k+1L, k+1L a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 # Print common digits - d, d1 = a/b, a1/b1 + d, d1 = a//b, a1//b1 while d == d1: g.put(int(d)) a, a1 = 10L*(a%b), 10L*(a1%b1) - d, d1 = a/b, a1/b1 + d, d1 = a//b, a1//b1 def test(): g = Generator(pi, ()) @@ -80,5 +87,6 @@ def test(): g.kill() while 1: print h.get(), + sys.stdout.flush() test() |