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
您可以使用我的^{} 类上的
iter()
方法来实现这一点。在pool.iter()
生成线程化函数返回值,直到所有修饰+调用的函数完成执行。装饰所有的异步函数,调用它们,然后通过pool.iter()
循环以捕捉发生的值。在示例:
简而言之,没有:没有线程就没有好的方法。在
有时ORMs会被某种peek函数或回调函数扩充,当数据可用时,这些函数或回调会发出信号。否则,您将需要生成线程来执行此操作。如果线程不是一个选项,您可以尝试将数据库库切换为异步库。在
相关问题 更多 >
编程相关推荐