Python共享的字符串内存用于多处理 [英] Python shared string memory for multiprocessing
问题描述
我正在尝试在我的Python进程之间使用一个共享的字符串变量,但是似乎由于我得到了coredumps和无效的内存值而做错了事.
I'm trying to use a shared string variable between my Python processes, but it seems that I'm doing something wrong since I'm getting coredumps and invalid memory values.
我使用multiprocessing.Value
创建一个ctypes.c_char_p
值,并使用value
属性进行访问.在我对Python文档的理解中,值属性应该是同步的,只要它是Value
的实例(与RawValue
的实例相反)即可.到目前为止,对吗?
I use multiprocessing.Value
to create a ctypes.c_char_p
value and use the value
attribute to access it. In my understanding of the Python docs the value attribute should be synchronized, as long it is an instance of Value
(contrary of an instance of RawValue
). Is that correct so far?
我创建了一个简短的示例来演示我对Value
的使用并在执行时显示不一致之处:
I've created a short example to demonstrate my use of Value
and to show the inconsistency while executing:
from multiprocessing import Process, Value
from ctypes import c_char_p
def process(v):
while True:
val = v.value
print val
while val == v.value:
pass
v = Value(c_char_p, None)
p = Process(target=process, args=(v,))
p.start()
for i in range(1,999):
v.value = str(i)
p.terminate()
推荐答案
我认为问题可能是由于使用Value(c_char_p)
保留字符串值引起的.如果您想要一个字符串,则应该只使用multiprocessing.Array(c_char)
.
I think the problem may have been caused by using Value(c_char_p)
to hold a string value. If you want a string, you should probably just use multiprocessing.Array(c_char)
.
这篇关于Python共享的字符串内存用于多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!