9 並發編程-(線程)-守護線程&互斥鎖
阿新 • • 發佈:2018-10-01
daemon 產生 主線程 click 守護線程 技術 分享 emp rgs
一 、守護線程
無論是進程還是線程,都遵循:守護xxx會等待主xxx運行完畢後被銷毀
需要強調的是:運行完畢並非終止運行
1、對主進程來說,運行完畢指的是主進程代碼運行完畢
2、對主線程來說,運行完畢指的是主線程所在的進程內所有非守護線程統統運行完畢,主線程才算運行完畢
詳細解釋:
1、主進程在其代碼結束後就已經算運行完畢了(守護進程在此時就被回收),
然後主進程會一直等非守護的子進程都運行完畢後回收子進程的資源(否則會產生僵屍進程),才會結束,
2、主線程在其他非守護線程運行完畢後才算運行完畢(守護線程在此時就被回收)。
因為主線程的結束意味著進程的結束,進程整體的資源都將被回收,而進程必須保證非守護線程都運行完畢後才能結束。
from threading import Thread import time def sayhi(name): time.sleep(2) print(‘%s say hello‘ %name) if __name__ == ‘__main__‘: t=Thread(target=sayhi,args=(‘egon‘,)) t.setDaemon(True) #必須在t.start()之前設置 t.start() print(‘主線程‘) print(t.is_alive()) 執行結果 主線程 TrueView Code
練習
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__‘: t1=Thread(target=foo) t2=Thread(target=bar) t1.daemonView Code=True t1.start() t2.start() print("main-------") 123 456 main------- end123 end456
二、互斥鎖
# 數據共享,競爭, from threading import Thread,Lock import time n = 100 def task(lock): global n lock.acquire() temp = n time.sleep(0.1)# 100個都停在這裏 n = temp - 1 lock.release() if __name__ == ‘__main__‘: t_l = [] lock = Lock() for i in range(100): t = Thread(target=task,args=(lock,)) t_l.append(t) t.start() for t in t_l: t.join() print(‘主‘,n) 主 0
9 並發編程-(線程)-守護線程&互斥鎖