gpt4 book ai didi

python - 使用方法 ThreadPoolExecutor.shutdown(wait=True), shutdown(wait=False) 和不使用这个方法有什么区别?

转载 作者:行者123 更新时间:2023-12-03 16:28:36 36 4
gpt4 key购买 nike

我无法理解差异。帮我看看这个区别。而ProcessPoolExecutor呢,他的行为是一样的吗?

def func(task):
do_something(task)

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks)
executor.shutdown(wait=True) # ok, here the main thread waits for others

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks)
executor.shutdown(wait=False) # here it doesn't wait and what can happens bad?

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks) # if i don't call shutdown ?

最佳答案

从文档:

If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing.



这涵盖了前两个示例。

对于第三个,因为 ThreadPoolExecutor遵守“上下文管理器”协议(protocol),您可以在 with 中使用它为了得到 shutdown 的声明执行退出 with 时自动调用方法堵塞。

默认为 True如果您省略参数 - 或者如果您将其用作上下文管理器,则在 with 中使用它无论 wait 的值如何, block 都是无用的.

[编辑]

i edited code. See pls, there are my final questions



您只需调用 shutdown方法,如果你想显式释放所有资源并确保没有新的调用 submitmap将会成功。如果你不调用shutdown(或者使用 ThreadPoolExecutor作为上下文管理器),资源可能只有在整个Python程序退出时才会被释放(直到所有未决的futures都完成后才会退出)。

调用 shutdownwait==True或使用 ThreadPoolExecutor作为上下文管理器将阻塞,直到所有未决的 future 都完成执行。

我能想到的唯一用例是调用 shutdown明确是:
executor = ThreadPoolExecutor(4)
try:
executor.map(func, tasks)
finally:
executor.shutdown(wait=False)

为了给出一些上下文,这是这个问题的第一个版本的代码片段:
def func(task):
do_something(task)

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
executor.map(func, tasks)
executor.shutdown(wait=True) # what is happening here?

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
executor.map(func, tasks)
executor.shutdown(wait=False) # what is happening here?

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
executor.map(func, tasks) # and without shutdown()?

请注意 tasks = [task for i in range(12)]是多余的 - 你可以只使用 executor.map(func, range(12))也是。

关于python - 使用方法 ThreadPoolExecutor.shutdown(wait=True), shutdown(wait=False) 和不使用这个方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28417525/

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