初始化和销毁​​Python多处理工作者


问题内容

我有一个要从Python调用多次的模型。该模型需要很长时间才能启动和关闭,但是只需很短的时间即可处理输入数据(在启动/关闭之间可以多次执行)。多重处理Pool()似乎是完成此工作的好方法,但是我很难让Model()类正确地销毁。

下面给出了程序代码的简化结构。实际上,init和del函数需要使用win32com.client模块做一些聪明的事情,而model.y变量是控制外部应用程序的句柄。

#!/usr/bin/env python

import multiprocessing
import random
import time

class Model():
    def __init__(self):
        self.y = random.randint(0,5) # simplification
        time.sleep(5) # initialisation takes a while...
    def __del__(self):
        del(self.y) # simplification
        time.sleep(1) # destruction isn't especially quick either

def init():
    global model
    model = Model()

def f(x): # worker function, runs quickly
    return model.y * x ** 2

def main():
    pool = multiprocessing.Pool(processes=2, initializer=init)
    it = pool.imap(f, range(4))
    for n in range(4):
        print it.next()
    pool.close()

if __name__ == '__main__':
    main()

我猜是因为在垃圾回收器中保留了一些引用,所以从未为Model()调用del函数。如何确保在程序结束时正确关闭模型?


问题答案:

johnthexiii的解决方案会在第一次运行worker函数时终止该模型。您可以提供单独的销毁功能:

import time

def g(x): # destroy function
    del model
    time.sleep(1) # to ensure, this worker does not pick too many
    return None

pool.close()添加之前

pool.map_async(g, range(2), 1) # if specified to have two processes before

我认为这不是一个非常“干净”的解决方案,但它应该可以工作。