#687648 from Robert Schuppenies: use classic division. From me: don't use string exception; flush stdout after printing

This commit is contained in:
Andrew M. Kuchling 2008-09-13 01:27:33 +00:00
parent 949f71b446
commit c2dc269288
1 changed files with 11 additions and 3 deletions

View File

@ -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()