我multiprocessing.Pool在Python 2.7. 我有大量只能在一天中的特定時間段內運行的作業。每項作業都需要一些時間。我想限制作業一次最多并行運行 n 個。
池功能可以很好地限制并行作業的數量,但是當我嘗試減少作業時它似乎有問題。當我在視窗結束時,我希望當前正在運行的作業完成它們的處理。我不希望開始新的作業。我一直在嘗試使用 來做到這一點Pool.close(),這確實讓我正在運行的行程按需要完成,但從實驗看來,即使在池關閉后,佇列中但尚未開始處理的作業仍將提交進行處理。
另一種選擇是Pool.terminate()主動關閉正在運行的作業,這與預期的行為背道而馳。
| 功能 | 允許正在運行的作業完成 | 阻止新作業開始 |
|---|---|---|
| .終止() | 不 | 是的 |
| 。關閉() | 是的 | 不 |
| 期望的行為 | 是的 | 是的 |
uj5u.com熱心網友回復:
首先,你不應該使用 Python2.7,它已經被棄用了一段時間。
您應該使用ProcessPoolExecutor來自concurrent.futures標準庫,并呼叫.shutdown()方法與cancel_futures標志被激活,讓執行者完成啟動作業,但取消所有待處理的作業。
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 個計劃的作業并未全部完成,只有一些是因為執行程式在兩者之間已關閉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312283.html
標籤:Python python-2.7 多处理 水池
上一篇:Python用裝飾器替換方法
