守護線程與守護進程
阿新 • • 發佈:2017-08-30
進程創建 init sse src 解釋 class children 拋出異常 none
一 守護進程
主進程創建守護進程
其一:守護進程會在主進程代碼執行結束後就終止
其二:守護進程內無法再開啟子進程,否則拋出異常:AssertionError: daemonic processes are not allowed to have children
註意:進程之間是互相獨立的,主進程代碼運行結束,守護進程隨即終止
from multiprocessing import Process import time import random class Piao(Process): def __init__(self,name): self.name=name super().__init__() def run(self): print(‘%s is piaoing‘ %self.name) time.sleep(random.randrange(1,3)) print(‘%s is piao end‘ %self.name) p=Piao(‘egon‘) p.daemon=True #一定要在p.start()前設置,設置p為守護進程,禁止p創建子進程,並且父進程代碼執行結束,p即終止運行 p.start() print(‘主‘)
import time迷惑人的例子def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") p1=Process(target=foo) p2=Process(target=bar) if __name__ == ‘__main__‘: p1.daemon=True p1.start() p2.start() print("main-------")
二 守護線程
fromthreading import Thread,currentThread from multiprocessing import Process import os,time,threading def talk1(): time.sleep(10) print(‘%s is running‘ %currentThread().getName()) def talk2(): time.sleep(2) print(‘%s is running‘ %currentThread().getName()) if __name__ == ‘__main__‘: t1=Thread(target=talk1) t2=Thread(target=talk2) t1.daemon=True t1.start() t2.start() print(‘主線程‘,os.getpid())
from threading import Thread import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") t1=Thread(target=foo) t2=Thread(target=bar) t1.daemon=True t1.start() t2.start() print("main-------")迷惑人的例子
三 守護進程與守護線程的區別
無論是進程還是線程,都遵循:守護xxx會等待主xxx運行完畢後被銷毀
需要強調的是:運行完畢並非終止運行
#1.對主進程來說,運行完畢指的是主進程代碼運行完畢 #2.對主線程來說,運行完畢指的是主線程所在的進程內所有非守護線程統統運行完畢,主線程才算運行完畢
詳細解釋:
#1 主進程在其代碼結束後就已經算運行完畢了(守護進程在此時就被回收),然後主進程會一直等非守護的子進程都運行完畢後回收子進程的資源(否則會產生僵屍進程),才會結束, #2 主線程在其他非守護線程運行完畢後才算運行完畢(守護線程在此時就被回收)。因為主線程的結束意味著進程的結束,進程整體的資源都將被回收,而進程必須保證非守護線程都運行完畢後才能結束。
守護線程與守護進程