【问题标题】:How can I make a generator prepare the next value in advance?如何让生成器提前准备下一个值?
【发布时间】:2016-07-17 15:45:20
【问题描述】:

我有一个生成器,它遍历大量元素并生成满足特定条件的元素。处理单个元素可能需要一段时间。一旦我产生了那个元素,再次在我的主函数中处理它需要一段时间。

这意味着当我循环遍历生成器时,我必须等待生成器找到满足所有条件的元素,然后让我的 main 函数处理它,然后冲洗并重复。我想通过在需要时立即提供下一个值来加快速度。

def generate(a, b):
    for stack in some_function(a, b):
        # Check for multiple conditions. This
        # takes a while.
        # I'd like to run this code in the
        # background while I process the
        # previous element down below.
        yield stack

for stack in generate(foo, bar):
    # Process the stack. This can take
    # a while too.

如何让生成器准备下一个值,以便在调用 next 时准备好?这可能是开箱即用的吗?我已经研究过协程和并发,但它们似乎与我的问题无关。

【问题讨论】:

  • 除非你在产生当前一个之前找到下一个,否则你不能。那个时间将不得不花在某处
  • @jonrsharpe 有没有办法将生成器放在单独的线程中以便它在后台运行?
  • 我刚刚遇到了this recipe,这似乎很相关。我将不得不研究 GIL,看看我是否可以使用类似的技术。

标签: python-3.x generator yield


【解决方案1】:

这是我想出的解决方案:

from queue import Queue
from threading import Thread

def generate(a, b, queue):
    for stack in some_function(a, b):
        # Check for multiple conditions.
        queue.put(stack)

queue = Queue()
thread = Thread(target=generate, args=(foo, bar, queue))
thread.start()

while thread.is_alive() or not queue.empty():
    stack = queue.get()
    # Process the stack.

如果堆栈的处理速度快于将它们添加到队列中的速度,则 while 循环仍会运行,因为线程仍处于活动状态。如果线程死了,那么只要队列为空,循环就会运行。这显然是一种解决方法,因为 generate 不再是生成器,但它可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2010-10-17
    • 2017-08-31
    • 2011-05-08
    • 2021-10-27
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多