通过fork()运行多个子进程的最佳方法是什么?

vic*_*orz 8 python linux

python脚本需要通过fork()生成多个子进程.所有这些子进程应该同时运行,父进程应该等待所有这些进程完成.有能力为"慢"的孩子设置一些超时会很好.在收集所有孩子后,父进程继续处理剩余的脚本.

解决这个问题的最佳方法是什么?谢谢.

eph*_*ent 11

简单的例子:

import os
chidren = []
for job in jobs:
    child = os.fork()
    if child:
        children.append(child)
    else:
        pass  # really should exec the job
for child in children:
    os.waitpid(child, 0)
Run Code Online (Sandbox Code Playgroud)

找出一个慢孩子是一个更多的工作; 您可以使用wait而不是waitpid从子列表中剔除返回的值,而不是依次等待每个值(如此处所示).如果alarm使用SIGALRM处理程序设置,则可以在指定的延迟后终止等待.这是所有标准的UNIX内容,而不是特定于Python的内容......


Fed*_*oni 5

Ephemient:你的代码中的每个孩子都会在他的工作结束后留在for循环中.他会一次又一次地岔开.而且,当孩子[]不是空的时候开始的孩子会在循环结束时等待他们的一些兄弟.最终有人会崩溃.这是一种解决方法:

import os, time

def doTheJob(job):
    for i in xrange(10):
        print job, i
        time.sleep(0.01*ord(os.urandom(1)))
        # random.random() would be the same for each process

jobs = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
imTheFather = True
children = []

for job in jobs:
    child = os.fork()
    if child:
        children.append(child)
    else:
        imTheFather = False
        doTheJob(job)
        break

# in the meanwhile 
# ps aux|grep python|grep -v grep|wc -l == 11 == 10 children + the father

if imTheFather:
    for child in children:
        os.waitpid(child, 0)
Run Code Online (Sandbox Code Playgroud)