2015-11-23 104 views
1

我嘗試使用下面的代碼如何使用os.fork()在循環中調用不同的函數?

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進程。例如,我想上面的代碼片斷在「func_map」略有變化擔任for循環這裏

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) 

回答

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 
+0

迭代從0到2,所以func_map = {0:f1,1:f2,2:f3} –

+0

是的。感謝您指出 – sunhs

+0

將'func_map'作爲一個列表,然後在枚舉(funcs)中爲我做func可能更有意義:'(如果我甚至需要 - 否則只是'func in funcs:'' 。 – lvc

相關問題