asyncio yield from concurrent.futures.Future of an Executor(来自并发的异步收益。未来。执行者的未来)
本文介绍了来自并发的异步收益。未来。执行者的未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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中实际运行。)
这篇关于来自并发的异步收益。未来。执行者的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:来自并发的异步收益。未来。执行者的未来
基础教程推荐
猜你喜欢
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
