首页 > 解决方案 > 如何在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

执行完期货任务后是否可以读取它?

标签: pythonpython-3.xasync-awaitpython-asyncioconcurrent.futures

解决方案


执行完期货任务后是否可以读取它?

在 asyncio 中,任务这个词有一个特殊的含义,指的是一个专门用于驱动协程的子类Future

在您的代码中,asyncio.gather()返回结果,并且您还拥有futures包含Future对象的变量,这些对象也可用于访问相同的结果。如果您需要访问其他信息(如原始信息funarg),您可以将其附加到适当的位置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

推荐阅读