我有一个消费者从我的发电机获取数据。现在消费者和生成器需要大约相同的时间来处理,所以我的总运行时间是:
(t_generator + t_consumer) * number_of_items
我现在想要在我的消费者处理当前项目的同时为下一个项目运行生成器,因此我的消费者不必等待t_generator
这通常如何在Python3中实现?
编辑(添加小样本):
g = my_generator() # cannot change this
intermediate = ??? # Do whatever you want. Maybe something like a queue which takes n from g and yields to consumer whenever ready?
processed p = consume(intermediate) # cannot change this
答案 0 :(得分:0)
答案 1 :(得分:0)
你可以线程化(因为你的制作人和消费者没有使用相同的资源):
from threading import Queue, Thread
g = my_generator() # cannot change this
q = Queue()
def fill_up():
for stuff in g:
q.put(stuff)
Thread(target=fill_up).start()
consume((q.get() for _ in range(2**32))