我不明白区别。帮我看看这个区别。那么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 ?
从文件中:
这包括前两个例子。在
对于第三种方法,由于
ThreadPoolExecutor
遵循“上下文管理器”协议,因此可以将其与with
语句一起使用,以便在执行退出with
块时自动调用shutdown
方法。在默认值是
True
,如果您省略了该参数-或者将其用作上下文管理器,那么无论wait
的值是多少,在with
块中使用它都是没有用的。在[编辑]
如果要显式释放所有资源并确保对}的新调用不会成功,则只调用
submit
或{shutdown
方法。如果不调用shutdown(或使用ThreadPoolExecutor
作为上下文管理器),则只有在整个Python程序退出时才会释放资源(在所有待定的未来完成之前,它不会退出)。在使用
wait==True
调用shutdown
或使用ThreadPoolExecutor
作为上下文管理器将阻塞,直到所有挂起的期货都执行完毕。在我能想到的显式调用
shutdown
的唯一用例是:为了提供一些上下文,以下是此问题第一版的代码片段:
^{pr2}$请注意,
tasks = [task for i in range(12)]
是多余的—您也可以只使用executor.map(func, range(12))
。在相关问题 更多 >
编程相关推荐