Python 多处理导致许多僵尸进程

Python Multiprocessing leading to many zombie processes

我一直在使用工作池实现 python 的多处理库。我实现了以下代码

import main1
t1 = time.time()
p = Pool(cores) 
result = p.map(main1, client_list[client])
if result == []:
    return []
p.close()
p.join()
print "Time taken in performing request:: ", time.time()-t1
return shorted(result)

但是,在 运行 一段时间后,我的应用程序出现了很多 运行 后台进程。这是在为我的应用

执行 ps aux 后的 snapshot

现在,我已经在 Whosebug 上阅读了很多类似的问题,例如 how to kill zombie processes created by multiprocessing module? which calls for using .join() which I have already implemented and I learned how to kill all these processes from here Python Multiprocessing Kill Processes。但我想知道我的代码可能出了什么问题。 我无法在 main1 函数中共享我的所有代码,但我已将整个代码块放在 try catch 块中,以避免主代码中的错误可能导致僵尸进程的情况。

def main1((param1, param2, param3)):
    try:
       resout.append(some_data) //resout in case of no error
    except:
        print traceback.format_exc()
        resout = []  //sending empty resout in case of error
    return resout

我对并行编程和调试问题的概念还是很陌生tricky.Any将不胜感激。

通常最常见的问题是创建了池但没有关闭。

我知道保证池关闭的最好方法是使用 try/finally 子句:

try:
    pool = Pool(ncores)
    pool.map(yourfunction, arguments)
finally:
    pool.close()
    pool.join()

如果您不想与 multiprocessing 纠缠不清,我写了一个名为 parmap 的简单程序包,它包装了多处理,让我(也可能是您)的生活更轻松。

pip install parmap

import parmap
parmap.map(yourfunction, arguments)

来自 parmap 用法部分:

  • 简单的并行示例:

    import parmap
    y1 = [myfunction(x, argument1, argument2) for x in mylist]
    y2 = parmap.map(myfunction, mylist, argument1, argument2)
    y1 == y2
    
  • 遍历元组列表:

    # You want to do:
    z = [myfunction(x, y, argument1, argument2) for (x,y) in mylist]
    z = parmap.starmap(myfunction, mylist, argument1, argument2)
    
    
    # You want to do:
    listx = [1, 2, 3, 4, 5, 6]
    listy = [2, 3, 4, 5, 6, 7]
    param = 3.14
    param2 = 42
    listz = []
    for (x, y) in zip(listx, listy):
        listz.append(myfunction(x, y, param1, param2))
    # In parallel:
    listz = parmap.starmap(myfunction, zip(listx, listy), param1, param2)