python - 如何在 Python 中使用 Managers() 在多个进程之间共享一个字符串?

标签 python multiprocessing shared-memory shared-state

我需要从主进程读取由 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/

相关文章:

python - 具有无限循环和队列的基本多处理

Python:TypeError:出于安全原因,不允许 Pickling AuthenticationString 对象

c# - 如何在 C# 应用程序中访问这种类型的 C++ 共享内存?

C++ boost库shared_memory_object undefined reference 'shm_open'

python - 将 Mixer 与 Flask-SQLAlchemy 结合使用

python - 在 PyKD 中获取可执行文件的模块

python - Python 中的列表

Python - 连续重新分配/更新类成员的正确方法

C++ 无法在我的 Windows 应用程序中重写共享内存。它分配新的内存

python - py.test : how to automatically detect an exception in a child process?