![](/img/trans.png)
[英]How to get currently running processes names from multiprocessing module in python
[英]How do you get multiprocessing Pool to not spin up new processes but also not terminate currently running processes?
我在Python 2.7
中使用 Python multiprocessing.Pool
class 。 我有大量作业只能在一天中的特定时间段运行。 每项工作都需要一些时间。 我想限制作业一次最多并行运行。
Pool 功能可以很好地限制并行作业的数量,但是当我试图结束作业时它似乎有问题。 当我在 window 结束时,我希望当前正在运行的作业完成它们的处理。 我不希望开始新的工作。 我一直在尝试使用Pool.close()
来做到这一点,这确实让我的运行进程按预期完成,但从实验看来,即使在队列中但尚未开始处理的作业仍将提交进行处理游泳池关闭了。
另一个选项Pool.terminate()
甚至会主动关闭正在运行的作业,这与预期的行为背道而驰。
Function | 允许运行的作业完成 | 阻止新工作开始 |
---|---|---|
.terminate() | 不 | 是的 |
。关闭() | 是的 | 不 |
期望的行为 | 是的 | 是的 |
首先,你不应该使用 Python2.7,它已经被弃用一段时间了。
您应该使用concurrent.futures
标准库中的ProcessPoolExecutor
并在激活cancel_futures
标志的情况下调用.shutdown()
方法,让执行程序完成已启动的作业,但取消任何未决的工作。
from concurrent.futures import ProcessPoolExecutor
parallel_jobs = 4 # The pool size
executor = ProcessPoolExecutor(parallel_jobs)
future_1 = executor.submit(work_1, argument_1)
...
future_n = executor.submit(work_n, argument_n)
...
# At some point when the time window ends and you need to stop jobs:
executor.shutdown(cancel_futures=True)
# Some futures such as future_n may have been cancelled here, you can check that:
if future_n.cancelled():
print("job n has been cancelled")
# Or you can try to get the result while checking for CancelledError:
try:
result_n = future_n.result()
except CancelledError:
print("job n hasn't finished in the given time window")
这是一个取消的例子:
from concurrent.futures import ThreadPoolExecutor, as_completed, wait
from time import sleep
# The job to execute concurrently
def foo(i: int) -> str:
sleep(0.2)
print(i)
return f"{i}"
e = ThreadPoolExecutor(4)
# Jobs are scheduled concurrently, this call does not block
futures = [e.submit(foo, i) for i in range(100)]
# Shutdown during execution and cancel pending jobs
e.shutdown(cancel_futures=True)
# Gather completed results
results = [f.result() for f in futures if not f.cancelled()]
print(results)
如果你执行这段代码,你会看到 100 个计划的作业并没有全部完成,只有一些是因为执行程序在两者之间被关闭了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.