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

2024-03-28 23:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

最好的解决办法是什么?谢谢。


Tags: 脚本进程时间孩子能力fork解决办法
3条回答

短暂的:代码中的每个孩子在其任务结束后都将停留在for循环中。他会一次又一次地叉子。此外,当children[]不为空时开始的子进程将尝试在循环结束时等待其某些兄弟。最终会有人崩溃。这是一个解决方法:

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)

你看过pyprocessing模块了吗?

简单示例:

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)

超时一个慢的子项需要做更多的工作;您可以使用wait,而不是waitpid,并从子项列表中剔除返回的值,而不是依次等待每个子项(如这里所示)。如果使用SIGALRM处理程序设置alarm,则可以在指定的延迟后终止等待。这都是标准的UNIX,不是Python特有的。。。

相关问题 更多 >