2017-04-21 29 views
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

+1

它看起來像你在一個12核心系統上運行。 map()將函數a()應用於列表中的12個項目,但列表中共有13個項目。由於'2'引發異常,因此程序在處理「1」之前暫停。看到[這個答案](http://stackoverflow.com/a/26096355)包裝異常,並在稍後提出。 – pclrk

+0

池不以這種方式工作。工作人員的數量與核心有關,應該在n和2n之間,其中n是核心數量。你可以把這麼多項傳遞給'map()',如果設置了'chunksize'參數,池將會在工作人員中用參數拆分調用,否則工作人員會從列表中選擇一個項並調用函數'a()'以前的項目等。請讓我知道如果我錯了 –

回答

1

默認情況下,池創建一些工人等於你的內核數量。當其中一個工作進程死亡時,可能會使分配給它的工作未完成。它也可能將輸出保留在永不會被刷新的緩衝區中。

.MAP圖案()是處理在工人異常和返回一些合適的誤差值,因爲.MAP的結果()應該是一個到一與所述輸入。

from multiprocessing import Pool 

def a(num): 
    try: 
     if(num == 2): 
      raise Exception("num can't be 2") 
     print(num, flush=True) 
     return num 
    except Exception as e: 
     print('failed', flush=True) 
     return e 

p = Pool() 
n=100 
results = p.map(a, range(n)) 

print("missing numbers: ", tuple(i for i in range(n) if i not in results)) 

這是另一個關於how exceptions propagate in multiprocessing.map workers的好信息。