【发布时间】:2012-03-07 12:03:10
【问题描述】:
以下代码使用multiprocessing 的Array 跨进程共享大量Unicode 字符串。如果我使用c_wchar_p作为类型,那么子进程的内存使用量大约是父进程使用的内存的四分之一(如果我改变Array中的条目数量,数量会改变)。
但是,如果我将 ctypes.Structure 与单个 c_wchar_p 字段一起使用,则子进程的内存使用量是恒定的并且非常低,而父进程的内存使用量会翻倍。
import ctypes
import multiprocessing
import random
import resource
import time
a = None
class Record(ctypes.Structure):
_fields_ = [('value', ctypes.c_wchar_p)]
def __init__(self, value):
self.value = value
def __str__(self):
return '(%s)' % (self.value,)
def child(i):
while True:
print "%ik memory used in child %i: %s" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, i, a[i])
time.sleep(1)
for j in xrange(len(a)):
c = a[j]
def main():
global a
# uncomment this line and comment the next to switch
#a = multiprocessing.Array(ctypes.c_wchar_p, [u'unicode %r!' % i for i in xrange(1000000)], lock=False)
a = multiprocessing.Array(Record, [Record(u'unicode %r!' % i) for i in xrange(1000000)], lock=False)
for i in xrange(5):
p = multiprocessing.Process(target=child, args=(i + 1,))
p.start()
while True:
print "%ik memory used in parent: %s" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, a[0])
time.sleep(1)
if __name__ == '__main__':
main()
使用 c_wchar_p 会产生以下输出:
363224k memory used in parent: unicode 0!
72560k memory used in child 5: unicode 5!
72556k memory used in child 3: unicode 3!
72536k memory used in child 1: unicode 1!
72568k memory used in child 4: unicode 4!
72576k memory used in child 2: unicode 2!
在此输出中使用记录结果:
712508k memory used in parent: (unicode 0!)
1912k memory used in child 1: (unicode 1!)
1908k memory used in child 2: (unicode 2!)
1904k memory used in child 5: (unicode 5!)
1904k memory used in child 4: (unicode 4!)
1908k memory used in child 3: (unicode 3!)
为什么?
【问题讨论】:
标签: python memory multiprocessing shared-memory