gpt4 book ai didi

python - 在子进程中的共享 c_wchar_p 中设置字符串值?

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:41 24 4
gpt4 key购买 nike

我有这样的情况:

主进程生成一些子进程,它们应该将结果写入字符串和数字类型的共享对象,对于数字类型没有问题,但对于字符串,值将丢失。

import multiprocessing as mp
from ctypes import Structure, c_double, c_wchar_p, c_int

# shared obj class
class SharedObj(Structure):
_fields_ = [('name', c_wchar_p), ('val', c_double) ]

def run_mp( values , lock , s ) :
for i in range( s , len( values ) , 2 ):
lock.acquire()
values[i].name = str( i ) # write the string value in the shared obj
values[i].val = float( i )
print( "tmp: %d" % i )
lock.release()

def main():
# creating the shared obj and mutex
values = mp.Array( SharedObj , [SharedObj() for i in range( 10 )] )
lock_j = mp.Lock()

# creating two sub-process form the function run_mp
p1 = mp.Process( target=run_mp , args=( values , lock_j , 0 ))
p2 = mp.Process( target=run_mp , args=( values , lock_j , 1 ))

p1.start()
p2.start()

p1.join()
p2.join()

for v in values:
print()
print( "res name: %s" % v.name )
print( "res val: %f " % v.val )


if __name__ == '__main__':
main()

因此包含c_double的共享对象中的字段被写在该字段中,但是在子进程rum-mp中生成的字符串(string values[i].name = str( i ) ) 会在主进程中丢失。

有没有保存子进程产生的字符串的方法?

此代码的输出如下所示:

主进程中生成的字符串是完全随机的。

tmp: 0
tmp: 2
tmp: 3
tmp: 4

res name: ����羍����羍
res val: 0.000000
res name: ����羍����羍
res val: 1.000000
res name:
res val: 2.000000 ....

最佳答案

这里是你的代码的一个稍微修改的版本:

#!/usr/bin/env pythonimport multiprocessing as mpdef run_mp( values ):    for c_arr, c_double in values:        c_arr.value = 'hello foo'        c_double.value = 3.14def main():    lock = mp.Lock()    child_feed = []    for i in range(10):        child_feed.append((            mp.Array('c', 15, lock = lock),            mp.Value('d', 1.0/3.0, lock = lock)        ))    p1 = mp.Process( target=run_mp , args=(child_feed,))    p2 = mp.Process( target=run_mp , args=(child_feed,))    p1.start()    p2.start()    p1.join()    p2.join()    for c_arr, c_double in child_feed:        print()        print( "res name: %s" % c_arr.value )        print( "res val: %f " % c_double.value )if __name__ == '__main__':    main()

看看http://docs.python.org/library/multiprocessing.html有一个使用字符数组的示例。

还有mmap模块允许共享内存http://docs.python.org/library/mmap.html但是有了这个,你必须通过信号量同步访问自己。如果您喜欢更简单的方法,只需使用管道即可。

关于python - 在子进程中的共享 c_wchar_p 中设置字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com