简体   繁体   中英

python multiprocessing set spawning process to wait

Is it possible to spawn some processes and set the spawning process to wait until the spawned processes finish? Bellow is an example I have used.

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"

will print

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

while I would like to have:

start main
messages from other services 
stop main

d.join() will block the main thread until d finishes. So, to get the order of print statements you desire, put the join s before print "stop main" :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM