Python 使用ThreadPoolExecutor.shutdown(wait=True)、shutdown(wait=False)方法与不使用此方法有什么区别?
我不明白两者的区别。帮我看看这个区别。那么ProcessPoolExecutor呢,他的行为也一样吗Python 使用ThreadPoolExecutor.shutdown(wait=True)、shutdown(wait=False)方法与不使用此方法有什么区别?,python,concurrent.futures,Python,Concurrent.futures,我不明白两者的区别。帮我看看这个区别。那么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
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 ?
从文档中:
如果wait为True,则此方法将不会返回,直到所有挂起的未来都已执行完毕,并且与执行器关联的资源已释放。如果wait为False,则此方法将立即返回,并且当所有挂起的未来都执行完毕时,将释放与执行器关联的资源。不管wait的值是多少,整个Python程序都不会退出,直到所有挂起的未来都执行完毕
这包括前两个例子
对于第三个,由于ThreadPoolExecutor
遵守“上下文管理器”协议,因此可以在with
语句中使用它,以便在执行退出with
块时自动调用shutdown
方法
如果省略该参数或将其用作上下文管理器,则默认值为True
,因此无论wait
的值是多少,在with
块中使用它都是无用的
[编辑]
我编辑代码。请看,这是我最后的问题 如果要明确释放所有资源并确保对
submit
或map
的新调用不会成功,则只能调用shutdown
方法。如果不调用shutdown(或使用ThreadPoolExecutor
作为上下文管理器),则只有在整个Python程序退出时才能释放资源(并且在完成所有挂起的未来操作之前不会退出)
使用wait==True
调用shutdown
,或使用ThreadPoolExecutor
作为上下文管理器,都将被阻止,直到所有挂起的期货都执行完毕
我能想到的唯一显式调用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))
。我已经读过了。方法分配只是为了等待所有线程完成吗?我不理解你的评论。shutdown
方法实际上只是说“不要让这个对象接受任何新任务,并允许它在已经分配的任务完成时释放资源。”wait
参数只控制方法调用是阻塞直到执行器完成“关闭”,还是在任何正在运行的进程完成时立即返回(异步)。我编辑了代码。请看,这是我最后的问题