【问题标题】:Why is the memory usage of a child (python multiprocessing) process so different when sharing a ctypes.Structure with a string vs. only a string?为什么在与字符串共享 ctypes.Structure 与仅使用字符串时,子进程(python 多处理)的内存使用量如此不同?
【发布时间】:2012-03-07 12:03:10
【问题描述】:

以下代码使用multiprocessingArray 跨进程共享大量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


    【解决方案1】:

    我不知道内存使用量的增加,但我不认为它真的在做你打算做的事情。

    如果您在父进程中修改a[i],子进程不会得到相同的值。

    最好不要在进程之间传递指针(这正是_p 类型的含义)。引用自multiprocessing docs:

    虽然可以将指针存储在共享内存中,但请记住,这将引用特定进程地址空间中的位置。但是,指针很可能在第二个进程的上下文中无效,并且尝试从第二个进程取消引用指针可能会导致崩溃。

    【讨论】:

    • 奇怪的是,它确实有效,至少在我的测试中,Python 对象似乎在父级中使用了更多的内存,而在子级中使用了更少的内存。知道这个问题的答案仍然很有趣。
    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2021-08-04
    • 2014-06-12
    • 2015-05-05
    • 2012-12-16
    相关资源
    最近更新 更多