29

我的理解是,如果输入了 try,finally 子句必须*always* 执行。

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

似乎终止一个进程的异常终止了父进程和兄弟进程,即使在其他进程中还需要完成进一步的工作。

为什么我错了?为什么这是正确的?如果这是正确的,应该如何安全地清理多进程 Python 中的资源?

4

3 回答 3

34

简短的回答:SIGTERM王牌finally

长答案:打开日志记录mp.log_to_stderr()

import random
import multiprocessing as mp
import time
import logging

logger=mp.log_to_stderr(logging.DEBUG)

def Process(x):
    try:
        logger.info(x)
        time.sleep(random.random())
        raise Exception('Exception: ' + x)
    finally:
        logger.info('Finally: ' + x)

result=mp.Pool(3).map(Process, ['1','2','3'])

日志输出包括:

[DEBUG/MainProcess] terminating workers

对应于以下代码multiprocessing.pool._terminate_pool

    if pool and hasattr(pool[0], 'terminate'):
        debug('terminating workers')
        for p in pool:
            p.terminate()

每个pinpool都是一个multiprocessing.Process,并且调用terminate(至少在非 Windows 机器上)调用 SIGTERM:

来自multiprocessing/forking.py

class Popen(object)
    def terminate(self):
        ...
            try:
                os.kill(self.pid, signal.SIGTERM)
            except OSError, e:
                if self.wait(timeout=0.1) is None:
                    raise

所以它归结为当一个try套件中的 Python 进程被发送一个SIGTERM.

考虑以下示例(test.py):

import time    
def worker():
    try:
        time.sleep(100)        
    finally:
        print('enter finally')
        time.sleep(2) 
        print('exit finally')    
worker()

如果您运行它,然后发送它 a SIGTERM,则该过程立即结束,无需进入finally套件,如无输出和无延迟所证明的那样。

在一个终端中:

% test.py

在第二个终端:

% pkill -TERM -f "test.py"

结果在第一个终端:

Terminated

SIGINT将其与进程发送( C-c)时发生的情况进行比较:

在第二个终端:

% pkill -INT -f "test.py"

结果在第一个终端:

enter finally
exit finally
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 14, in <module>
    worker()
  File "/home/unutbu/pybin/test.py", line 8, in worker
    time.sleep(100)        
KeyboardInterrupt

结论:SIGTERM王牌finally

于 2011-10-09T12:48:50.200 回答
4

unutbu回答明确解释了为什么会得到你观察到的行为。但是,应该强调的是,发送 SIGTERM 只是因为如何实现。如果您可以避免使用,那么您可以获得您想要的行为。这是一个借来的例子multiprocessing.pool._terminate_poolPool

from multiprocessing import Process
from time import sleep
import random

def f(x):
    try:
        sleep(random.random()*10)
        raise Exception
    except:
        print "Caught exception in process:", x
        # Make this last longer than the except clause in main.
        sleep(3)
    finally:
        print "Cleaning up process:", x

if __name__ == '__main__':
    processes = []
    for i in range(4):
        p = Process(target=f, args=(i,))
        p.start()
        processes.append(p)
    try:
        for process in processes:
            process.join()
    except:
        print "Caught exception in main."
    finally:
        print "Cleaning up main."

发送 SIGINT 后,示例输出为:

Caught exception in process: 0
^C
Cleaning up process: 0
Caught exception in main.
Cleaning up main.
Caught exception in process: 1
Caught exception in process: 2
Caught exception in process: 3
Cleaning up process: 1
Cleaning up process: 2
Cleaning up process: 3

请注意,该finally子句适用于所有进程。如果您需要共享内存,请考虑使用QueuePipeManager或一些外部存储,例如redisor sqlite3

于 2014-12-04T08:39:35.390 回答
1

finally除非您return从中重新引发原始异常。然后引发异常Pool.map并终止您的整个应用程序。子流程被终止,您看不到其他异常。

您可以添加一个return来吞下异常:

def Process(x):
  try:
    print x
    sleep(random.random())
    raise Exception('Exception: ' + x)
  finally:
    print 'Finally: ' + x
    return

然后,当发生异常时None,您的结果中应该有。map

于 2011-10-09T01:58:19.983 回答