1
我在玩Python和多处理。我试图确定什么happends如果工人抛出一个异常,所以我写了下面的代码:工作进程中的例外
def a(num):
if(num == 2):
raise Exception("num can't be 2")
print(num)
p = Pool()
p.map(a, [2, 1, 3, 4, 5, 6, 7, 100, 100000000000000, 234, 234, 5634, 0000])
输出
3
4
5
7
6
100
100000000000000
234
234
5634
0
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "/usr/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar
return list(map(*args))
File "<stdin>", line 3, in a
Exception: Error, num can't be 2
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/multiprocessing/pool.py", line 260, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "/usr/lib/python3.5/multiprocessing/pool.py", line 608, in get
raise self._value
Exception: Error, num can't be 2
如果你能看到这是印有“2”的数字不在那里,但为什么不是第1号呢?
注意:我使用Python 3.5.2在Ubuntu
它看起来像你在一个12核心系统上运行。 map()将函数a()应用于列表中的12个项目,但列表中共有13个项目。由于'2'引发异常,因此程序在处理“1”之前暂停。看到[这个答案](http://stackoverflow.com/a/26096355)包装异常,并在稍后提出。 – pclrk
池不以这种方式工作。工作人员的数量与核心有关,应该在n和2n之间,其中n是核心数量。你可以把这么多项传递给'map()',如果设置了'chunksize'参数,池将会在工作人员中用参数拆分调用,否则工作人员会从列表中选择一个项并调用函数'a()'以前的项目等。请让我知道如果我错了 –