如何解决Python 多处理池:在完成任何 k 个作业后终止进程
我有一个函数,可以使用 Pool.starmap() 调用 n
进程。我想在 k
中的任何 n
完成后终止所有进程。我该如何实施?
解决方法
使用 Pool.imap_unordered
或 concurrent.futures.as_completed
可以更轻松地完成 list
的已提交任务。无论哪种情况,解决方案都是一样的;迭代结果迭代器 k
次(例如使用 itertools.slice
),然后终止 Pool
(在 Executor
情况下,调用 shutdown(cancel_futures=True)
,或确保取消手动完成所有未完成的任务)。例如,而不是:
with Pool() as pool:
results = pool.starmap(func,makes_tuples())
将所有结果作为单个操作收集并消除您在中途停止处理的能力,您可以:
from itertools import islice
# Defined at global scope as simple wrapper to allow non-starmap functions to
# be used with iterators of argument tuples
def starcall_func(args):
return func(*args)
...
with Pool() as pool:
results = list(islice(pool.imap_unordered(starcall_func,makes_tuples()),k))
# When with exits,pool is terminated automatically,and only k results were collected
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。