如何在Python中使用经理()在多个过程中共享字符串



我需要读取通过Multiprocessing.Process实例编写的字符串。我已经使用经理和队列将参数传递给流程,因此使用经理似乎很明显,但是经理不支持字符串:

Manager()返回的经理将支持类型列表,dict, 命名空间,锁,rlock,信号量,有限semaphore,条件,事件, 队列,值和数组。

使用多处理模块中的经理使用字符串代表的状态?

多处理的经理可以容纳值,而该值又可以容纳C_CHAR_P类型的实例:

>>> 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!'

对于Python 3,使用C_WCHAR_P代替C_CHAR_P

另请参见:使用我很难找到的原始解决方案发布。

因此,经理可以在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!'

只需将字符串放在dict中:

d = manager.dict()
d['state'] = 'xyz'

由于字符串本身是不可变的,直接共享一个不会那么有用。

最新更新