下面的代码按预期执行,将总完成时间返回几乎为零,因为它不会等待线程完成每一项任务。
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
return f'Done Sleeping...{seconds}'
executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')但是使用with命令,它确实会等待:
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]为什么?with有这种多线程行为的原因是什么?
发布于 2020-05-30 16:27:29
concurrent.futures没有被很好地记录下来。当您创建一个执行器时,必须关闭它来终止它的线程或进程。该代码将通过向线程推送None命令来指示线程退出,然后等待它们完成。在第一个例子中,如果添加了executor.shutdown(),就会看到延迟。它就在那里-程序还是用了10秒才退出的。
执行器可以用作上下文管理器(它作为__enter__和__exit__方法)。当它退出"with“块时,将调用__exit__,然后它将为您执行shutdown调用。
https://stackoverflow.com/questions/62105222
复制相似问题