如何有效地迭代多个生成器?

时间:2012-10-15 23:08:52

标签: python generator

我有三个不同的生成器,可以从网络上生成数据。因此,每次迭代可能需要一段时间才能完成。

我想混合调用生成器,并考虑roundrobin(找到here)。 问题是每次通话都会被阻止,直到完成为止。

有没有办法在不阻塞的情况下同时遍历所有生成器?

2 个答案:

答案 0 :(得分:5)

您可以使用ThreadPool课程中的iter()方法执行此操作。

pool.iter()产生线程函数返回值,直到所有修饰的+被调用函数完成执行。装饰所有的异步函数,调用它们,然后遍历pool.iter()以捕获它们发生的值。

示例:

import time
from threadpool import ThreadPool
pool = ThreadPool(max_threads=25, catch_returns=True)

# decorate any functions you need to aggregate
# if you're pulling a function from an outside source
# you can still say 'func = pool(func)' or 'pool(func)()
@pool
def data(ID, start):
    for i in xrange(start, start+4):
        yield ID, i
        time.sleep(1)

# each of these calls will spawn a thread and return immediately
# make sure you do either pool.finish() or pool.iter()
# otherwise your program will exit before the threads finish
data("generator 1", 5)
data("generator 2", 10)
data("generator 3", 64)

for value in pool.iter():
    # this will print the generators' return values as they yield
    print value

答案 1 :(得分:1)

简而言之,不:没有线程就没有好办法。

有时,ORM会增加某种偷看功能或回调功能,以便在数据可用时发出信号。否则,您需要生成线程才能执行此操作。如果线程不是一个选项,您可能会尝试将数据库库切换为异步数据库。