问题描述
我需要从主流程中读取multiprocessing.Process实例编写的字符串.我已经使用管理器和队列将参数传递给进程,因此使用管理器似乎很明显,但管理器不支持字符串:
I need to read strings written by multiprocessing.Process instances from the main process. I already use Managers and queues to pass arguments to processes, so using the Managers seems obvious, but Managers do not support strings:
如何使用多处理模块中的管理器共享由字符串表示的状态?
How do I share state represented by a string using Managers from the multiprocessing module?
推荐答案
多重处理的管理者可以持有值,该值又可以容纳 ctypes模块中的c_char_p :
multiprocessing's Managers can hold Values which in turn can hold instances of the type c_char_p from the ctypes module:
>>> 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!'
另请参阅:发布原始解决方案,我很难找到.
See also: Post with the original solution that I had a hard time finding.
因此,可以使用管理器在Python的多个进程下共享一个字符串,如下所示:
So a Manager can be used to share a string beneath multiple processes in Python like this:
>>> 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!'
这篇关于如何在Python中使用Managers()在多个进程之间共享字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!