2011-04-26 101 views
2

我想插入並更新使用psycopg和multiprocessing幾百萬行。通過http://initd.org/psycopg/docs/usage.html#thread-and-process-safety中發現的文檔,每個孩子都有自己的連接到數據庫。multiprocessing + psycopg2殭屍兒童

但是在執行過程中,只有一個孩子在其他人變成殭屍時運行。在本身的腳本是非常簡單,這裏是相同的修剪版本,

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有逐步升級的鎖,但它看起來像它的情況並非如此。我錯過了明顯的東西嗎?

+0

是什麼get_db_connection辦?它是創建一個新的連接還是返回一個共享連接?根據你選擇的文檔,它應該創建一個新的連接。 – 2011-04-26 20:02:42

+0

Philip,不,它不使用共享連接。爲每個分叉的子項創建一組新的連接和光標。 (應該是create_db_connection()) – sudharsh 2011-04-27 05:00:57

回答

0

您的進程變成殭屍,因爲作業已完成但進程未加入。執行這個時候,3個過程後

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) 

打印,他們會停下來,他們成爲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) 
+0

塞德里克,我遇到的問題是隻有一個孩子會跑,而其他人成爲殭屍。 問題btw原來是Postgres – sudharsh 2011-04-30 07:45:57

+0

@sudharsh的僵局,你是否設法追蹤並克服了僵局? – pkaleta 2013-01-31 16:48:59