0

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

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() 中?

4

1 回答 1

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()返回一个实例方法。实例方法不能正确腌制,并且multiprocessing必须保存(腌制)和加载(取消腌制)共享数据项才能将它们的值从一个进程传递到另一个进程。例如,请参阅Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map()Overcoming Python's limits about instance methods。特别注意第二个答案之一:找出一些要发送/共享的状态可能会更好,而不是整个实例。例如,如果ident一个进程的 足够了,你可以这样做:

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

效果很好。

于 2013-07-15T08:38:52.930 回答