系统相关
首页 > 系统相关> > 如何使用Python中的Managers()在多个进程之间共享字符串?

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

作者:互联网

我需要读取主进程中的multiprocessing.Process实例编写的字符串.我已经使用Managers和队列将参数传递给进程,所以使用Managers似乎很明显,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.

如何使用多处理模块中的Managers共享由字符串表示的状态?

解决方法:

多处理的管理器可以容纳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!'

另见:Post with the original solution我很难找到.

因此,可以使用Manager在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!'

标签:shared-state,python,multiprocessing,shared-memory
来源: https://codeday.me/bug/20191005/1856937.html