python - 如何在python中从未来检索任务?
问题描述
假设我有以下代码可以并行运行多个任务。
with concurrent.futures.ThreadPoolExecutor(max_workers=connections) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
fun,
arg
)
for i in range(connections)
]
for result in await asyncio.gather(*futures):
# I want to access the futures task here
pass
执行完期货任务后是否可以读取它?
解决方案
执行完期货任务后是否可以读取它?
在 asyncio 中,任务这个词有一个特殊的含义,指的是一个专门用于驱动协程的子类。Future
在您的代码中,asyncio.gather()
返回结果,并且您还拥有futures
包含Future
对象的变量,这些对象也可用于访问相同的结果。如果您需要访问其他信息(如原始信息fun
或arg
),您可以将其附加到适当的位置Future
或使用 dict 来映射它。例如:
futures = []
for conn in connections:
fut = loop.run_in_executor(executor, fun, arg)
fut.conn = conn # or other info you need
await asyncio.wait(futures)
# at this point all the futures are done, and you can use future.result()
# to access the result of an individual future, and future.conn to obtain
# the connection the future was created for
推荐阅读
- scala - 重复记录移动到 Spark Scala 中的其他数据帧
- css - 带边距顶部的 css 选择选项
- node.js - 需要在我的 Ubuntu 操作系统中使用 nodejs 运行单独的 power shell 脚本
- python-3.x - 如果字符串在键或值中匹配,则删除字典中的键和值
- python - 是否有选择指定字符串后的前 2 个单词的功能?
- java - 如何使用 JSON 格式发布 ManyToOne 和 OneToOne 实体?
- sql - SSIS 不插入多于一行
- c# - 如何使用 Fizzler / HtmlAgilityPack 选择具有命名空间的 html 元素?
- osgi - OSGi 中的 bytebuddy rebase 与子类和错误名称/NoClassDefFoundError
- data-binding - Haxe:具有抽象字段访问方法的绑定模式