在多处理Manager.dict()中存储过程对象

时间:2013-07-15 07:54:42

标签: python multiprocessing

我创建了这个示例程序来概括我面临的问题

import multiprocessing
from multiprocessing import Manager

def f (_print):
    print _print
    manager = multiprocessing.Manager()
    dict = manager.dict()
    dict['process_obj'] = multiprocessing.current_process()
    print dict

if __name__ == '__main__':
    process = multiprocessing.Process(target=f, args= ('hello function', ))
    process.start()
    process.join()

那么如何在多处理Manager.dict()中存储一个进程对象?

1 个答案:

答案 0 :(得分:1)

我假设您正在谈论收到此错误:

hello function
Process Process-1:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/local/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "mp2.py", line 8, in f
    dict['process_obj'] = multiprocessing.current_process()
  File "<string>", line 2, in __setitem__
  File "/usr/local/lib/python2.7/multiprocessing/managers.py", line 758, in _callmethod
    conn.send((self._id, methodname, args, kwds))
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed

(在问题中包含“我得到的东西”和“我希望得到的东西”通常是一个好主意。)

这里的根本问题是multiprocessing.current_process()返回一个实例方法。实例方法没有正确地进行pickle,multiprocessing必须保存(pickle)和加载(unpickle)共享数据项,以便将它们的值从一个进程传递到另一个进程。例如,请参阅Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map()Overcoming Python's limitations regarding instance methods。特别注意第二个答案之一:最好找出一些发送/共享的状态,而不是整个实例。例如,如果进程的ident足够,则可以执行以下操作:

    dict['process_obj'] = multiprocessing.current_process().ident

工作正常。