本文介绍了python多处理设置生成过程等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以生成某些进程并将生成进程设置为等到生成进程完成?贝娄是我使用的一个例子.
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"
将打印
start main
Starting: daemon 2809
stop main
Starting: non-daemon 2810
Exiting : non-daemon 2810
我想拥有:
start main
messages from other services
stop main
推荐答案
d.join()
将阻塞主线程,直到d
完成.因此,要获得所需的打印语句的顺序,请将join
s放在print "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"
这篇关于python多处理设置生成过程等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!