来自并发的异步收益。未来。执行者的未来 [英] asyncio yield from concurrent.futures.Future of an Executor

查看:23
本文介绍了来自并发的异步收益。未来。执行者的未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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中实际运行。)

这篇关于来自并发的异步收益。未来。执行者的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆