Python:等待所有concurrent.futures.ThreadPoolExecutor的未来 [英] Python: Wait on all of `concurrent.futures.ThreadPoolExecutor`'s futures

查看:317
本文介绍了Python:等待所有concurrent.futures.ThreadPoolExecutor的未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经给了 concurrent.futures.ThreadPoolExecutor 一堆任务,我想等到它们全部完成后再继续操作。我该如何做,而不必保存所有期货并对其调用等待? (我想要对执行程序执行操作。)

I've given concurrent.futures.ThreadPoolExecutor a bunch of tasks, and I want to wait until they're all completed before proceeding with the flow. How can I do that, without having to save all the futures and call wait on them? (I want an action on the executor.)

推荐答案

只需调用 Executor.shutdown


关闭(wait = True)

shutdown(wait=True)

向执行者发出信号,当执行中的未决期货完成时,应该使用释放
的资源。关机后调用
Executor.submit() Executor.map() b引发 RuntimeError

Signal the executor that it should free any resources that it is using when the currently pending futures are done executing. Calls to Executor.submit() and Executor.map() made after shutdown will raise RuntimeError.

如果等待时间为 True ,则直到所有未完成的期货都执行完
并释放了与执行者相关的资源后,该方法才会返回。

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.

但是,如果您在列表中跟踪期货,则可以避免使用 futures.wait() 函数:

However if you keep track of your futures in a list then you can avoid shutting the executor down for future use using the futures.wait() function:


concurrent.futures.wait(fs,timeout = None,return_when = ALL_COMPLETED)

concurrent.futures.wait(fs, timeout=None, return_when=ALL_COMPLETED)

等待 Future 实例(可能由不同的
Executor 实例创建),由 fs 完成。返回一个命名的2元组
集。第一组名为完成,包含在等待完成之前
完成(完成或取消)的期货。第二组
名为not_done,包含未完成的期货。

Wait for the Future instances (possibly created by different Executor instances) given by fs to complete. Returns a named 2-tuple of sets. The first set, named done, contains the futures that completed (finished or were cancelled) before the wait completed. The second set, named not_done, contains uncompleted futures.

请注意,如果您不提供超时,它会等待所有期货都完成。

note that if you don't provide a timeout it waits until all futures have completed.

您还可以使用 futures.as_completed() ,但是您必须遍历它。

You can also use futures.as_completed() instead, however you'd have to iterate over it.

这篇关于Python:等待所有concurrent.futures.ThreadPoolExecutor的未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆