-
Notifications
You must be signed in to change notification settings - Fork 38
/
background_generator.py
45 lines (36 loc) · 1.16 KB
/
background_generator.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
# Authors:
# Christian F. Baumgartner ([email protected])
# Lisa M. Koch ([email protected])
# Adapted from this stack overflow answer https://stackoverflow.com/questions/7323664/python-generator-pre-fetch
# by Winston Ewert
# Usage: If you have a generator function (i.e. one that ends with yield <something>, you can wrap that
# function in the BackgroundGenerator.
#
# For example:
#
# for batch in BackgroundGenerator(iterate_minibatches(data)):
# do something to batch
#
import threading
import queue
class BackgroundGenerator(threading.Thread):
def __init__(self, generator,max_prefetch=1):
threading.Thread.__init__(self)
self.queue = queue.Queue(max_prefetch)
self.generator = generator
self.daemon = True
self.start()
def run(self):
for item in self.generator:
self.queue.put(item)
self.queue.put(None)
def next(self):
next_item = self.queue.get()
if next_item is None:
raise StopIteration
return next_item
# Python 3 compatibility
def __next__(self):
return self.next()
def __iter__(self):
return self