python多处理集生成进程等待

时间:2013-07-28 14:18:55

标签: 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

1 个答案:

答案 0 :(得分: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"