来自并发的异步收益。未来。执行者的未来
问题描述
我有一个long_task函数,它运行大量CPU限制的计算,我想通过使用新的异步框架使其异步。产生的long_task_async函数使用ProcessPoolExecutor将工作卸载到不受GIL约束的不同进程。
问题在于,由于某种原因,从ProcessPoolExecutor.submit返回的concurrent.futures.Future实例抛出了TypeError。这是设计好的吗?这些期货是否与asyncio.Future类不兼容?有什么解决办法?
我还注意到生成器是不可拾取的,因此向ProcessPoolExecutor提交Cou例程将失败。这个问题也有什么干净的解决方案吗?
import asyncio
from concurrent.futures import ProcessPoolExecutor
@asyncio.coroutine
def long_task():
yield from asyncio.sleep(4)
return "completed"
@asyncio.coroutine
def long_task_async():
with ProcessPoolExecutor(1) as ex:
return (yield from ex.submit(long_task)) #TypeError: 'Future' object is not iterable
# long_task is a generator, can't be pickled
loop = asyncio.get_event_loop()
@asyncio.coroutine
def main():
n = yield from long_task_async()
print( n )
loop.run_until_complete(main())
解决方案
您要使用loop.run_in_executor,它使用concurrent.futures执行器,但将返回值映射到asyncio未来。
asyncioPEPsuggests thatconcurrent.futures.Future将来可能会发展成__iter__方法,因此也可以与yield from一起使用,但目前该库已设计为只需要yield from支持,不需要更多支持。(否则某些代码将无法在3.3中实际运行。)
相关文章