1 # Generator implementation using threads
6 class Killed(Exception):
11 def __init__(self
, func
, args
):
12 self
.getlock
= thread
.allocate_lock()
13 self
.putlock
= thread
.allocate_lock()
14 self
.getlock
.acquire()
15 self
.putlock
.acquire()
20 thread
.start_new_thread(self
._start
, ())
25 self
.putlock
.acquire()
28 apply(self
.func
, (self
,) + self
.args
)
34 self
.getlock
.release()
36 # Called by producer for each value; raise Killed if no more needed
39 raise TypeError, 'put() called on killed generator'
41 self
.getlock
.release() # Resume consumer thread
42 self
.putlock
.acquire() # Wait for next get() call
46 # Called by producer to get next value; raise EOFError if no more
49 raise TypeError, 'get() called on killed generator'
50 self
.putlock
.release() # Resume producer thread
51 self
.getlock
.acquire() # Wait for value to appear
53 raise EOFError # Say there are no more values
56 # Called by consumer if no more values wanted
59 raise TypeError, 'kill() called on killed generator'
61 self
.putlock
.release()
65 return Generator(self
.func
, self
.args
)
68 k
, a
, b
, a1
, b1
= 2L, 4L, 1L, 12L, 4L
71 p
, q
, k
= k
*k
, 2L*k
+1L, k
+1L
72 a
, b
, a1
, b1
= a1
, b1
, p
*a
+q
*a1
, p
*b
+q
*b1
77 a
, a1
= 10L*(a
%b
), 10L*(a1
%b1
)
84 for i
in range(10): print g
.get(),