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中实际运行。)
这篇关于来自并发的异步收益。未来。执行者的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:来自并发的异步收益。未来。执行者的未来


猜你喜欢
- python-m http.server 443--使用SSL? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01