我需要读取主进程中的multiprocessing.Process实例写的字符串。我已经使用Managers和队列将参数传递给进程,因此使用Managers似乎很明显,but Managers do not support strings:
Manager()返回的经理将支持类型列表,dict, Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event, 队列,价值和数组。
如何使用多处理模块中的Managers共享字符串表示的状态?
答案 0 :(得分:13)
多处理的管理员可以保留Values,而c_char_p可以保存来自ctypes模块的Post with the original solution类型的实例:
>>> import multiprocessing
>>> import ctypes
>>> v = multiprocessing.Value('c', "Hello, World!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/multiprocessing/__init__.py", line 253, in Value
return Value(typecode_or_type, *args, **kwds)
File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 99, in Value
obj = RawValue(typecode_or_type, *args)
File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 73, in RawValue
obj.__init__(*args)
TypeError: one character string expected
>>> cstring = multiprocessing.Value(ctypes.c_char_p, "Hello, World!")
>>> cstring
<Synchronized wrapper for c_char_p(166841564)>
>>> cstring.value
'Hello, World!'
另请参阅:{{3}}我很难找到。
因此,可以使用Manager在Python中的多个进程下共享字符串,如下所示:
>>> from multiprocessing import Process, Manager, Value
>>> from ctypes import c_char_p
>>>
>>> def greet(string):
>>> string.value = string.value + ", World!"
>>>
>>> if __name__ == '__main__':
>>> manager = Manager()
>>> string = manager.Value(c_char_p, "Hello")
>>> process = Process(target=greet, args=(string,))
>>> process.start()
>>> process.join()
>>> print string.value
'Hello, World!'
答案 1 :(得分:5)
只需将字符串放在dict
:
d = manager.dict()
d['state'] = 'xyz'
由于字符串本身是不可变的,因此直接共享字符串不会有用。