我需要讀取由主進程中的多進程實例編寫的字符串。我已經使用管理和隊列參數傳遞給過程,所以使用經理似乎很明顯,but Managers do not support strings:如何使用Python中的Managers()在多個進程中共享一個字符串?
由經理返回的經理()將支持類型列表,字典, 命名空間,鎖,RLOCK,信號燈, BoundedSemaphore,條件,事件, 隊列,值和數組。
如何使用多處理模塊中的管理器共享由字符串表示的狀態?
我需要讀取由主進程中的多進程實例編寫的字符串。我已經使用管理和隊列參數傳遞給過程,所以使用經理似乎很明顯,but Managers do not support strings:如何使用Python中的Managers()在多個進程中共享一個字符串?
由經理返回的經理()將支持類型列表,字典, 命名空間,鎖,RLOCK,信號燈, BoundedSemaphore,條件,事件, 隊列,值和數組。
如何使用多處理模塊中的管理器共享由字符串表示的狀態?
多的管理者可以持有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我有一個很難找到。
所以一個經理可以用來共享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!'
簡單的把字符串中dict
:
d = manager.dict()
d['state'] = 'xyz'
爲字符串本身是不可變的,直接共享一個將不會有用。
我想知道爲什麼這個工作(共享一個指針),並從源頭上了解到'managers.Value'實際上並不實際使用'typecode'參數。該字符串未轉換爲「c_char_p」。 'multiprocessing.Value'工作原理非常不同。 –