子进程设置为守护进程后,在主进程代码执行结束(而非进程退出)后,子进程就终止。
如果子进程没有设置为守护进程,那么主进程会等子进行结束才结束主进程。
1. 守护进程的设置必须在start前设置。
2. 守护进程无法再开启子进程。
from multiprocessing import Process import time def work(n): time.sleep(n) print(‘守护进程。。。。。‘) if __name__ == ‘__main__‘: p = Process(target=work, args=(3,)) p.daemon = True p.start() # p.join() print(‘主进程内‘) # 输出结果: # 主进程内 # 说明:子进程都没有执行到,因为主进程已经结束。
验证守护进程无法再开启子进程:
from multiprocessing import Process import time def work(n): time.sleep(n) print(‘守护进程。。。。。‘) pp1 = Process(target=time.sleep, args=(3,)) pp1.start() if __name__ == ‘__main__‘: p = Process(target=work, args=(3,)) p.daemon = True p.start() p.join() print(‘主进程内‘) # 输出结果: # 主进程内 # 说明:子进程都没有执行到,因为主进程已经结束。
输出结果:
报错:
AssertionError: daemonic processes are not allowed to have children 守护进程不能有子进程
守护进程。。。。。 Process Process-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/data/bealla/work/luffy/projects/zuoye/network/test2.py", line 9, in work pp1.start() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 103, in start ‘daemonic processes are not allowed to have children‘ AssertionError: daemonic processes are not allowed to have children 主进程内
守护进程练习题:
守护进程在主进程代码执行完毕后就终止。
from multiprocessing import Process import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") if __name__ == ‘__main__‘: p1=Process(target=foo) p2=Process(target=bar) p1.daemon=True p1.start() p2.start() print("main-------")
输出:
main------- 456 end456
原文地址:https://www.cnblogs.com/beallaliu/p/9190411.html
时间: 2024-10-12 08:28:21