How to share a string amongst multiple processes using Managers() in Python?

回眸只為那壹抹淺笑 提交于 2019-11-29 12:30:47

问题


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:

A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and Array.

How do I share state represented by a string using Managers from the multiprocessing module?


回答1:


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.

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!'



回答2:


Simply put the string in a dict:

d = manager.dict()
d['state'] = 'xyz'

As strings themselves are immutable, sharing one directly would not be as useful.



来源:https://stackoverflow.com/questions/21290960/how-to-share-a-string-amongst-multiple-processes-using-managers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!