私の理解では、try が入力された場合、 finally 句は*常に* 実行する必要があります。
import random
from multiprocessing import Pool
from time import sleep
def Process(x):
try:
print x
sleep(random.random())
raise Exception('Exception: ' + x)
finally:
print 'Finally: ' + x
Pool(3).map(Process, ['1','2','3'])
予想される出力は、8 行目までに単独で出力される x ごとに、'Finally x' が出現することです。
出力例:
$ python bug.py
1
2
3
Finally: 2
Traceback (most recent call last):
File "bug.py", line 14, in <module>
Pool(3).map(Process, ['1','2','3'])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 225, in map
return self.map_async(func, iterable, chunksize).get()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 522, in get
raise self._value
Exception: Exception: 2
他のプロセスで実行する必要がある追加の作業があるにもかかわらず、1 つのプロセスを終了する例外が親プロセスと兄弟プロセスを終了するようです。
なぜ私は間違っているのですか?なぜこれが正しいのですか?これが正しい場合、マルチプロセス Python でリソースを安全にクリーンアップするにはどうすればよいですか?