一、守护进程

  主进程创建守护进程,守护进程的主要的特征为:①守护进程会在主进程代码执行结束时立即终止;②守护进程内无法继续再开子进程,否则会抛出异常。

实例:

from multiprocessing import Process
from threading import Thread
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-------") #打印该行则主进程代码结束,则守护进程p1应该被终止,可能会有p1任务执行的打印信息123,因为主进程打印main----时,p1也执行了,但是随即被终止

  注:打印最后一行主进程代码结束,则守护进程p1应该被终止,可能会有p1任务执行的打印信息‘start123’,因为主进程打印main-时,p1也执行了,但是随即被终止。

from threading import Thread
import time
def foo():  # 守护线程
    print(123)
    time.sleep(1)
    print("end123")

def bar():
    print(456)
    time.sleep(3)
    print("end456")

if __name__ == '__main__':
    p1=Thread(target=foo)
    p2=Thread(target=bar)

    p1.daemon=True
    p1.start()
    p2.start()
    print("main-------")
# 123
# 456
# main-------
# end123
# end456
守护线程

相关文章:

  • 2018-07-12
  • 2022-03-07
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-07-18
猜你喜欢
  • 2021-05-19
  • 2022-12-23
  • 2021-10-27
  • 2021-05-20
  • 2021-05-15
  • 2021-06-11
  • 2022-12-23
相关资源
相似解决方案