forked from halxp1/seq2seq_chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadedgenerator.py
76 lines (63 loc) · 1.8 KB
/
threadedgenerator.py
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
from threading import Thread
from queue import Queue
class ThreadedGenerator(object):
def __init__(self,iterator,
sentinel=object(),
queue_maxsize=0,
daemon=False):
self._iterator = iterator
self._sentinel = sentinel
self._queue = Queue(maxsize=queue_maxsize)
self._thread = Thread(
name=repr(iterator),
target=self._run
)
self._thread.daemon= daemon
self._started=False
def __repr__(self):
return 'ThreadedGenerator({!r})'.format(self._iterator)
def _run(self):
try:
for value in self._iterator:
if not self._started:
return
self._queue.put(value)
finally:
self._queue.put(self._sentinel)
def close(self):
self._started = False
try:
while True:
self._queue.get(timeout=30)
except KeyboardInterrupt as e:
raise e
except:
pass
def __iter__(self):
self._started = True
self._thread.start()
for value in iter(self._queue.get,self._sentinel):
yield value
self._thread.join()
self._started=False
def __next__(self):
if not self._started:
self._started = True
self._thread.start()
value = self._queue.get(timeout=30)
if value ==self._sentinel:
raise StopIteration()
return value
def test():
def gene():
i=0
while True:
yield i
i+=1
t = gene()
test = ThreadedGenerator(t,queue_maxsize=10)
for _ in range(10):
print(next(test))
test.close()
if __name__ == '__main__':
test()