多进程的管理器可以持有 Values,而这些值可以持有来自 ctypes 模块的 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中可以使用Manager来共享字符串在多个进程之间,像这样:
>>> 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!'
managers.Value
实际上并没有使用typecode
参数。该字符串没有被转换成c_char_p
。而multiprocessing.Value
的工作方式则大相径庭。 - Janne Karilas = multiprocessing.Value(c_char_p, "old string")
,但是s.value = "new string"
经常会丢失指针。我还尝试了另一种解决方案Array('c', fixed_length)
,它更加稳定。 - John LinManager
,它是行不通的,因为c_wchar_p
只是一个指向数据的指针,所以当另一个进程访问它时,就会直接出现“分段错误”。更多的说明可以在这里找到:https://dev59.com/hWjWa4cB1Zd3GeqPoj_-#12343115。是的,正如之前的评论中提到的那样,`Array('c', fixed_length)` 对我也起作用。 - VladVin期望字节或整数地址,而不是str实例
。 - Ryan GlennArray('c', fixed_length)
的示例代码吗? - undefined