【问题标题】:memory usage with python multiprocessingpython多处理的内存使用情况
【发布时间】:2012-10-16 23:05:34
【问题描述】:

multiprocessing.Process 生成的进程消耗的内存是否会在进程加入后被释放?

我想到的场景大概是这样的:

from multiprocessing import Process
from multiprocessing import Queue
import time
import os

def main():
  tasks = Queue()  
  for task in [1, 18, 1, 2, 5, 2]:
    tasks.put(task)

  num_proc = 3           # this many workers @ each point in time
  procs = []
  for j in range(num_proc):
     p = Process(target = run_q, args = (tasks,))  
     procs.append(p)
     p.start()

  # joines a worker once he's done
  while procs:
    for p in procs:
        if not p.is_alive():
            p.join()        # what happens to the memory allocated by run()?  
            procs.remove(p)
            print p, len(procs)
    time.sleep(1)  

def run_q(task_q):
    while not task_q.empty():  # while's stuff to do, keep working
        task = task_q.get()
        run(task)

def run(x):       # do real work, allocates memory
    print x, os.getpid()
    time.sleep(3*x)


if __name__ == "__main__":
  main()  

在实际代码中,tasks 的长度远远大于 CPU 内核的数量,每个 task 都是轻量级的,不同的任务占用的 CPU 时间(几分钟到几天)和内存量大不相同(从花生到几 GB)。所有这些内存都是run 的本地内存,无需共享它——所以问题是,一旦run 返回和/或加入进程,它是否会被释放。

【问题讨论】:

    标签: python multiprocessing


    【解决方案1】:

    当进程终止时,进程消耗的内存被释放。在您的示例中,这发生在 run_q() 返回时。

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多