我尝试使用以下代码
import os
def sum1(a):
print "We are in the child process with PID= %d"%os.getpid()
for j in range(100000000):
m=j
print "Sum: ",sum(a)
os._exit(0)
def mul(a):
print "We are in the child process with PID= %d"%os.getpid()
k=1
for j in range(100000000):
m=j
for i in a:
k=k*i
print "Multiplication: ",k
def parent(a):
while True:
print "We are in the parent process with PID= %d"%os.getpid()
newpid=os.fork()
if newpid == 0:
sum1(a)
else:
mul(a)
if input() == 'q': break
a=[12,12,12,12]
parent(a)
但是在这段代码中,它只为一个函数[sum1()]创建了分叉进程。我想在循环中执行fork进程,每次调用不同的函数。例如,我想在循环
中使用不同的分叉进程调用以下三个函数def f1(a):
print a
def f2(b):
print b
def f3(c):
print c
类似于
for i in range(3):
pid = os.fork()
if pid == 0:
f1(a) # then call f2(b) in next iteration and then f3(c)in last iteration
os._exit(0)
答案 0 :(得分:2)
func_map = {0: f1, 1: f2, 2: f3}
def parent(a):
for i in range(3):
pid = os.fork()
if pid == 0:
func_map[i](a)
return