【问题标题】:multiprocessing + psycopg2 zombie children多处理 + psycopg2 僵尸孩子
【发布时间】:2011-04-26 17:49:24
【问题描述】:

我正在尝试使用 psycopg 和多处理插入和更新几百万行。根据http://initd.org/psycopg/docs/usage.html#thread-and-process-safety 中的文档,每个孩子都有自己与数据库的连接。

但在行刑过程中,只有一个孩子跑,其他孩子变成僵尸。脚本本身非常简单,这里是一个精简版,

import os
import psycopg2

from multiprocessing import Process


def _target(args):
    # Each forked process will have its own connection
    # http://initd.org/psycopg/docs/usage.html#thread-and-process-safety
    conn = get_db_connection()

    # Stuff seems to execute till this point in all the children
    print os.getpid(), os.getppid()

    # Do some updates here. After this only one child is active and running
    # Others become Zombies after a while.


if __name__ == '__main__':
    args = "Foo"
    for i in xrange(3):
        p = Process(target=_target, args=(args,))
        p.start()

我还通过查看pg_locks 来检查表是否具有升级锁,但看起来情况并非如此。我错过了什么明显的东西吗?

【问题讨论】:

  • get_db_connection 是做什么的?是创建新连接还是返回共享连接?根据您找到的文档,它应该正在创建一个新连接。
  • Philip,不,它不使用共享连接。为每个分叉的孩子创建一组新的连接和游标。 (应该是 create_db_connection() )

标签: python multiprocessing psycopg2 zombie-process


【解决方案1】:

您的进程成为僵尸,因为有作业已完成但进程未加入。 我用这个单一的测试重现了你的问题(我添加了睡眠来模拟长时间的工作):

import os
import time
from multiprocessing import Process

def _target(args):
    print os.getpid(), os.getppid()
    time.sleep(2)
    print os.getpid(), "will stop"

if __name__ == '__main__':
    args = "Foo"
    for i in xrange(3):
        p = Process(target=_target, args=(args,))
        p.start()
    import time
    time.sleep(10)

执行此操作时,在 3 个进程打印它们将停止后,它们将进入 ps 视图(它们不再移动,但并没有真正死,因为父亲仍然持有它们)。

如果我用这个替换主要部分,我就没有僵尸了:

if __name__ == '__main__':
    args = "Foo"
    processes = []
    for i in xrange(3):
        p = Process(target=_target, args=(args,))
        processes.append(p)
        p.start()
    for p in processes:
        p.join()
    import time
    time.sleep(10)

【讨论】:

  • Cedric,我的问题是只有一个孩子会逃跑,而其他孩子会变成僵尸。顺便说一句,这个问题原来是 Postgres 中的死锁
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2020-08-02
  • 2011-09-19
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
相关资源
最近更新 更多