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)
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)
短暂的:代码中的每个孩子在其任务结束后都将停留在for循环中。他会一次又一次地叉子。此外,当children[]不为空时开始的子进程将尝试在循环结束时等待其某些兄弟。最终会有人崩溃。这是一个解决方法:
你看过pyprocessing模块了吗?
简单示例:
超时一个慢的子项需要做更多的工作;您可以使用
wait
,而不是waitpid
,并从子项列表中剔除返回的值,而不是依次等待每个子项(如这里所示)。如果使用SIGALRM
处理程序设置alarm
,则可以在指定的延迟后终止等待。这都是标准的UNIX,不是Python特有的。。。相关问题 更多 >
编程相关推荐