我想使用multiprocessing.Pool并行应用一个函数。问题是,如果一个函数调用触发了分段错误,那么Pool将永远挂起。有没有人知道如何创建一个池来检测何时发生这样的事情并引发错误?
下面的例子展示了如何重现它(需要scikit-learn > 0.14)
import numpy as np
from sklearn.ensemble import gradient_boosting
import time
from multiprocessing import Pool
class Bad(object):
tree_ = None
def fit_one(i):
if i == 3:
# this will segfault
bad = np.array([[Bad()] * 2], dtype=np.object)
gradient_boosting.predict_stages(bad,
np.random.rand(20, 2).astype(np.float32),
1.0, np.random.rand(20, 2))
else:
time.sleep(1)
return i
pool = Pool(2)
out = pool.imap_unordered(fit_one, range(10))
# we will never see 3
for o in out:
print o发布于 2015-11-20 10:07:59
正如评论中所描述的,如果您使用concurrent.Futures.ProcessPoolExecutor而不是multiprocessing.Pool,这只适用于Python3。
如果您坚持使用Python2,我找到的最佳选择是在Pool.apply_async和Pool.map_async返回的result对象上使用timeout参数。例如:
pool = Pool(2)
out = pool.map_async(fit_one, range(10))
for o in out:
print o.get(timeout=1000) # allow 1000 seconds max只要对子进程完成一项任务所需的时间有一个上限,这个方法就有效。
发布于 2015-11-20 10:12:55
这是一个known bug, issue #22393, in Python。在修复之前,只要您使用multiprocessing.pool,就没有任何有意义的变通方法。在这个链接上有一个补丁,但是它还没有集成到主发行版中,所以没有稳定的Python发行版来解决这个问题。
发布于 2015-03-05 16:33:51
与使用Pool().imap()相比,您可能更愿意使用Process()手动创建子进程。我敢打赌,返回的对象将允许您获取任何孩子的活动状态。如果他们挂了,你会知道的。
https://stackoverflow.com/questions/24370930
复制相似问题