我需要从主进程读取由 multiprocessing.Process 实例写入的字符串。我已经使用管理器和队列将参数传递给进程,因此使用管理器似乎很明显,but Managers do not support strings :
A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and Array.
如何使用多处理模块中的管理器共享由字符串表示的状态?
最佳答案
multiprocessing 的管理器可以容纳 Values反过来又可以容纳 c_char_p 类型的实例来自 ctypes 模块:
>>> 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
另请参阅:Post with the original solution我很难找到。
因此,在 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!'
关于python - 如何在 Python 中使用 Managers() 在多个进程之间共享一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21290960/