-
Notifications
You must be signed in to change notification settings - Fork 71
/
threaded_generator.py
35 lines (28 loc) · 996 Bytes
/
threaded_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
#!/usr/bin/env python3
"""Threaded generator. https://github.com/Lasagne/Lasagne/issues/12#issuecomment-59494251"""
def threaded_generator(generator, num_cached=50):
"""Implements threaded generator to produce batches in background thread.
# Arguments
generator: an object exposing generator interface.
# Yields
Objects generated by generator.
"""
from queue import Queue
qu = Queue(maxsize=num_cached)
sentinel = object() # guaranteed unique reference
# define producer (putting items into queue)
def producer():
for item in generator:
qu.put(item)
qu.put(sentinel)
# start producer (in a background thread)
import threading
thread = threading.Thread(target=producer)
thread.daemon = True
thread.start()
# run as consumer (read items from queue, in current thread)
item = qu.get()
while item is not sentinel:
yield item
qu.task_done()
item = qu.get()