我有一个模型,我从 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()
del 函数永远不会为 Model() 调用,我猜是因为垃圾收集器中保存了一些引用。如何确保模型在程序结束时正确关闭?
最佳答案
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
我不认为这是一个非常“干净”的解决方案,但它应该有效。
关于python - 初始化和销毁 Python 多处理 worker ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13046956/