使用这种方法有什么区别ThreadPoolExecutor.shutdown(wait=True)、关闭(wait=False)并且不使用这个?

2024-05-14 17:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白区别。帮我看看这个区别。那么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 ?

Tags: inmapfortaskheredefrangetasks
1条回答
网友
1楼 · 发布于 2024-05-14 17:13:14

从文件中:

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遵循“上下文管理器”协议,因此可以将其与with语句一起使用,以便在执行退出with块时自动调用shutdown方法。在

默认值是True,如果您省略了该参数-或者将其用作上下文管理器,那么无论wait的值是多少,在with块中使用它都是没有用的。在

[编辑]

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

如果要显式释放所有资源并确保对submit或{}的新调用不会成功,则只调用shutdown方法。如果不调用shutdown(或使用ThreadPoolExecutor作为上下文管理器),则只有在整个Python程序退出时才会释放资源(在所有待定的未来完成之前,它不会退出)。在

使用wait==True调用shutdown或使用ThreadPoolExecutor作为上下文管理器将阻塞,直到所有挂起的期货都执行完毕。在

我能想到的显式调用shutdown的唯一用例是:

executor = ThreadPoolExecutor(4)
try:
    executor.map(func, tasks)
finally:
    executor.shutdown(wait=False)

为了提供一些上下文,以下是此问题第一版的代码片段:

^{pr2}$

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

相关问题 更多 >

    热门问题