gpt4 book ai didi

python - 如何在Python中从 future 检索任务?

转载 作者:行者123 更新时间:2023-12-01 01:49:03 25 4
gpt4 key购买 nike

假设我有以下代码来并行运行多个任务。

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

Future 任务执行后是否可以读取它?

最佳答案

Is it possible to read the the futures' task once it has been executed?

在 asyncio 中,单词 task 有专门的含义,指的是 class子类 Future专门用于驱动协程。

在您的代码中,asyncio.gather() 返回结果,并且您还有包含 Future 对象的 futures 变量,该对象可以也可用于访问相同的结果。如果您需要访问其他信息(例如原始的 funarg),您可以将其附加到适当的 Future 或使用字典来映射它。例如:

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

关于python - 如何在Python中从 future 检索任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com