【发布时间】:2015-08-01 07:23:20
【问题描述】:
我已经搜索过,但在其他地方找不到这个问题的答案。希望我没有错过任何东西。
我正在尝试使用 Python 多处理来并行批量运行一些专有模型。比如说,我有 200 次模拟,我想一次批量运行 10-20 次。我的问题是,如果两个模型碰巧在相同/相似的时间启动,专有软件就会崩溃。我需要在多处理产生的进程之间引入延迟,以便每个新模型运行在开始前等待一点。
到目前为止,我的解决方案是在子进程启动模型运行之前引入随机时间延迟。但是,这只会降低任意两次运行同时开始的概率,因此在尝试处理大量模型时仍然会遇到问题。因此,我认为时间延迟需要内置到代码的多处理部分中,但我无法找到任何文档或示例。
编辑:我使用的是 Python 2.7
这是我目前的代码:
from time import sleep
import numpy as np
import subprocess
import multiprocessing
def runmodels(arg):
sleep(np.random.rand(1,1)*120) # this is my interim solution to reduce the probability that any two runs start at the same time, but it isn't a guaranteed solution
subprocess.call(arg) # this line actually fires off the model run
if __name__ == '__main__':
arguments = [big list of runs in here
]
count = 12
pool = multiprocessing.Pool(processes = count)
r = pool.imap_unordered(runmodels, arguments)
pool.close()
pool.join()
【问题讨论】:
-
imap_unordered()返回一个迭代器,您应该使用它,例如for result in pool.imap_unordered(...): -
在这种情况下,我通常会在该循环中做什么(即在 for 语句之后的行中)?
-
处理单个模拟的结果(如果有)和/或报告进度 (
'\r{x} out of {y} simulations done')。 -
重点是,您应该明确地使用迭代器(无论实际的
multiprocessing实现是什么)。如果您不需要结果;使用deque(r, maxlen=0)。
标签: python multithreading batch-file multiprocessing