python - 我如何等待 ThreadPoolExecutor.map 完成

标签 python python-3.x python-multithreading

我有以下经过简化的代码:

import concurrent.futures

pool = concurrent.futures.ThreadPoolExecutor(8)

def _exec(x):
    return x + x

myfuturelist = pool.map(_exec,[x for x in range(5)])

# How do I wait for my futures to finish?

for result in myfuturelist:
    # Is this how it's done?
    print(result)

#... stuff that should happen only after myfuturelist is
#completely resolved.
# Documentation says pool.map is asynchronous

有关 ThreadPoolExecutor.map 的文档薄弱。帮助会很棒。

谢谢!

最佳答案

ThreadPoolExecutor.map 的调用不会阻塞,直到它的所有任务都完成。使用 wait做这个。

from concurrent.futures import wait, ALL_COMPLETED
...

futures = [pool.submit(fn, args) for args in arg_list]
wait(futures, timeout=whatever, return_when=ALL_COMPLETED)  # ALL_COMPLETED is actually the default
do_other_stuff()

您还可以在 pool.map 返回的生成器上调用 list(results) 以强制执行评估(这是您在原始示例中所做的) .但是,如果您实际上没有使用任务返回的值,wait 是可行的方法。

关于python - 我如何等待 ThreadPoolExecutor.map 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532411/

相关文章:

python - 如何在 Jupyter 笔记本中运行 Python asyncio 代码?

python - 属性与前面的属性赋值操作的右侧值不同

python - Pandas 获取月底的数据?

python - NLTK 无法找到 gs 文件

python - 尝试将 dict_values 转换为 ipdb 中的列表时出错

python-3.x - 线程和异步: Task was destroyed but it is pending

python - 如何对传感器进行编程以中断主线程或Python中的程序

python - 如何返回线程的第一个参数以及线程从队列的返回?

python - 如何使用 lambda 打印字符串列表?

python-3.x - 如何在 sympy 中表示不同的非数字符号?