2015-02-09 29 views
-1

我不明白区别。帮助我观察这种差异。那么ProcessPoolExecutor呢,他的行为是一样的吗?使用方法ThreadPoolExecutor.shutdown(wait = True),shutdown(wait = False)和不使用此方法之间有什么区别?

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 ? 
+2

https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown – njzk2 2015-02-09 19:19:02

+0

我读过了。只是等待所有线程完成的方法分配? – r45i 2015-02-09 19:23:51

+0

我不明白你的意见。 – njzk2 2015-02-09 19:24:37

回答

4

从文档:

如果等待为真,那么这个方法将不会返回,直到所有悬而未决的期货执行完毕,并与执行相关的资源已被释放。如果wait为False,那么这个方法将立即返回,并且当所有待执行的期货完成执行时,与执行器相关的资源将被释放。无论等待的价值如何,整个Python程序都将不会退出,直到所有挂起的期货都执行完毕。

这涵盖了前两个例子。

对于第三个,因为ThreadPoolExecutor坚持“上下文管理”协议,您可以以有shutdown方法自动呼吁尽快执行退出with块用它沿着with声明。

如果您省略参数 - 或者如果您将其用作上下文管理器,则在with块内使用该参数无论wait的值是多少,则默认值为True

[编辑]

我编辑代码。见PLS,也有我的最终问题

,如果你想明确地释放所有的资源,并确保submitmap没有新的呼叫会成功,你只叫shutdown方法。如果你没有调用shutdown(或者使用ThreadPoolExecutor作为上下文管理器),那么只有当整个Python程序退出时才会释放资源(并且在所有未完成的期货完成之前它不会退出)。

调用shutdownwait==True或使用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))

+0

这个解释更好,thx – r45i 2015-02-10 11:15:52

相关问题