python3 守護進程daemon


 什么是守護進程?

import time
from multiprocessing import Process


def func(name):
    while 1:
        time.sleep(0.5)
        print(f"我是{name}")


if __name__ == '__main__':
    p1 = Process(target=func, args=("進程1",))
    p1.daemon = True  # 必須寫在子進程啟動前,主進程守護子進程,主進程結束,子進程直接結束
    p1.start()
    time.sleep(2)
    print("主進程執行結束。")

執行結果:

我是進程1
我是進程1
我是進程1
主進程執行結束。

主進程守護子進程,主進程結束,子進程直接結束

關於守護進程需要強調兩點:

其一:守護進程會在主進程代碼執行結束后就終止

其二:守護進程內無法再開啟子進程,否則拋出異常

 

守護進程必須在開啟子進程前開啟

from multiprocessing import Process
import time


def task(name):
    print("%s is running" % name)
    time.sleep(3)
    print("%s is done" % name)


if __name__ == '__main__':
    t = Process(target=task, args=("子進程1",))
    # 守護進程必須在開啟子進程前開啟
    t.daemon = True
    t.start()
    time.sleep(1)
    print("")

執行結果:

子進程1 is running
主

 

在主進程代碼執行完畢,只要出現打印主進程信息,p1就不會執行或者死掉

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

 

接着看下面的程序

from multiprocessing import Process
import time


def foo(name):
    print("%s 開始" % name)
    time.sleep(1)
    print("%s end123" % name)


if __name__ == '__main__':
    p1 = Process(target=foo, args=("進程1",))
    p2 = Process(target=foo, args=("進程2",))
    p3 = Process(target=foo, args=("進程3",))

    p1.daemon = True
    p1.start()
    p2.start()
    p3.start()
    print("main------")

執行結果:

main------
進程3 開始
進程2 開始
進程3 end123
進程2 end123

 

再看最后一個程序

import time
from multiprocessing import Process


def func(name, sec):
    print(name, 123)
    time.sleep(sec)
    print(name, "123end")


if __name__ == '__main__':
    p1 = Process(target=func, args=("進程1", 1))
    p2 = Process(target=func, args=("進程2", 2))
    p3 = Process(target=func, args=("進程3", 3))
    p1.daemon = True  # 必須在start()之前設置守護進程
    p1.start()
    p2.start()
    p3.start()
    time.sleep(0.5)
    print("主進程結束,主進程還得等待其他子進程(非守護進程)結束才行")

 執行結果:

進程1 123
進程3 123
進程2 123
主進程結束,主進程還得等待其他子進程(非守護進程)結束才行
進程2 123end
進程3 123end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM