2013-07-28 114 views
1

是否有可能產生一些進程並設置產卵進程等到產生的進程完成?貝婁是我用過的一個例子。python multiprocessing設置產卵過程等待

import multiprocessing 
import time 
import sys 

def daemon(): 
    p = multiprocessing.current_process() 
    print 'Starting:', p.name, p.pid 
    sys.stdout.flush() 
    time.sleep(2) 
    print 'Exiting :', p.name, p.pid 
    sys.stdout.flush() 

def non_daemon(): 
    p = multiprocessing.current_process() 
    print 'Starting:', p.name, p.pid 
    sys.stdout.flush() 
    print 'Exiting :', p.name, p.pid 
    sys.stdout.flush() 

if __name__ == '__main__': 
    d = multiprocessing.Process(name='daemon', target=daemon) 
    d.daemon = True 

    n = multiprocessing.Process(name='non-daemon', target=non_daemon) 
    n.daemon = False 

    print "start main" 
    d.start() 
    time.sleep(1) 
    n.start() 
    print "stop main" 

將打印

start main 
Starting: daemon 2809 
stop main 
Starting: non-daemon 2810 
Exiting : non-daemon 2810 

,而我想有:

start main 
messages from other services 
stop main 

回答

5

d.join() will block the main thread直到d結束。 因此,要得到你想要的打印語句的順序,把join小號print "stop main"前:

print "start main" 
d.start() 
time.sleep(1) 
n.start() 
d.join() 
n.join() 
print "stop main" 
+0

@danizgod:'join'是這樣的動作通常的名字,所以你也能找到'join'在'Thread'和'Queue'中 –