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

标签 python python-3.x async-await python-asyncio concurrent.futures

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

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/

相关文章:

python - 你如何使用pygame创建按钮?

python - 如何解决 Python 中 `len` 函数的限制?

python - Python 中 Eratosthenes 的惰性筛选

python-3.x - Django Rest Framework - 当用户不是对象所有者时拒绝用户推送

c# - UI线程有什么特别之处?

python - 有没有办法对discord.py wait_for() 使用异步检查函数?

javascript - 异步/等待, "unresolved variable or type await"

python - 将多个 EPS 图像加载到 matplotlib 子图

python - CMake 源代码构建 - Python 文件

python - 如何将 Django 模型的实例保存到我的数据库中