【发布时间】:2013-09-09 12:35:11
【问题描述】:
我正在尝试使用 nose 编写测试以设置某些内容 使用多处理计算。
我有这个目录结构:
code/
tests/
tests.py
tests.py 看起来像这样:
import multiprocessing as mp
def f(i):
return i ** 2
pool = mp.Pool()
out = pool.map(f, range(10))
def test_pool():
"""Really simple test that relies on the output of pool.map.
The actual tests are much more complicated, but this is all
that is needed to produce the problem."""
ref_out = map(f, range(10))
assert out == ref_out
if __name__ == '__main__':
test_pool()
从code 目录运行,python tests/tests.py 通过。
nosetests tests/tests.py 未能完成。它启动了,但从来没有通过对pool.map的调用而只是挂起。
为什么会这样?最简单的解决方案是什么?
【问题讨论】:
-
nose在运行测试时可能正在使用一些线程和/或日志记录。当与 UNIX 系统上的多处理混合时,这可能导致死锁。这不是 python 实现的问题,而是fork()函数本身的问题,它只分叉当前线程,请参阅this 答案以获得更详细的解释。 -
我相信唯一的(?)解决方案是模拟
multiprocessing模块。实际上,我看不到您的示例正在测试什么。它实际上是multiprocessing.Pool.map方法的单元测试,而不是f函数的单元测试! -
这是重现我的错误的最小示例。我正在测试大量使用
pool.map的结果作为输入的其他东西。 -
在多个核心上计算
map是否重要?如果不是,则将pool.map替换为普通的map。 -
显然可以解决它!但是,这不是一个选项:将
pool.map的使用视为问题的约束。
标签: python testing multiprocessing python-nose