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
未来。
asyncio
PEPsuggests thatconcurrent.futures.Future
将来可能会发展成__iter__
方法,因此也可以与yield from
一起使用,但目前该库已设计为只需要yield from
支持,不需要更多支持。(否则某些代码将无法在3.3中实际运行。)
这篇关于来自并发的异步收益。未来。执行者的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:来自并发的异步收益。未来。执行者的未来


基础教程推荐
猜你喜欢
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01