對python 多線程中的守護線程與join的用法詳解
多線程:在同一個時間做多件事
守護線程:如果在程序中將子線程設(shè)置為守護線程,則該子線程會在主線程結(jié)束時自動退出,設(shè)置方式為thread.setDaemon(True),要在thread.start()之前設(shè)置,默認是false的,也就是主線程結(jié)束時,子線程依然在執(zhí)行。
thread.join():在子線程完成運行之前,該子線程的父線程(一般就是主線程)將一直存在,也就是被阻塞
實例:
#!/usr/bin/python # encoding: utf-8 import threading from time import ctime,sleep def func1(): count=0 while(True): sleep(1) print 'fun1 ',count count = count+1 def func2(): count=0 while(True): sleep(2) print 'fun2 ',count count = count+1 threads = [] t1 = threading.Thread(target=func1) threads.append(t1) t2 = threading.Thread(target=func2) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start()
上面這段程序執(zhí)行后,將不會有任何輸出,因為子線程還沒來得及執(zhí)行,主線程就退出了,子線程為守護線程,所以也就退出了。
修改后的程序:
#!/usr/bin/python # encoding: utf-8 import threading from time import ctime,sleep def func1(): count=0 while(True): sleep(1) print 'fun1 '+str(count) count = count+1 def func2(): count=0 while(True): sleep(2) print 'fun2 '+str(count) count = count+1 threads = [] t1 = threading.Thread(target=func1) threads.append(t1) t2 = threading.Thread(target=func2) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join()
可以按照預(yù)期執(zhí)行了,主要join的調(diào)用要加在循環(huán)外,不然程序只會執(zhí)行第一個線程。
print 的部分改成+,是為了避免輸出結(jié)果中出現(xiàn)類似fun1 fun2 49 這種情況,這是由于程序執(zhí)行太快,用‘,'間隔相當(dāng)于執(zhí)行了兩次print ,在這期間另一個線程也執(zhí)行了print,所以導(dǎo)致了重疊。
以上這篇對python 多線程中的守護線程與join的用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
matplotlib事件處理基礎(chǔ)(事件綁定、事件屬性)
這篇文章主要介紹了matplotlib事件處理基礎(chǔ)(事件綁定、事件屬性),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(一)
這篇文章主要介紹了python網(wǎng)絡(luò)編程基礎(chǔ)知識,需要的朋友可以參考下2014-06-06Python數(shù)據(jù)結(jié)構(gòu)與算法之列表(鏈表,linked list)簡單實現(xiàn)
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)與算法之列表(鏈表,linked list)簡單實現(xiàn),具有一定參考價值,需要的朋友可以了解下。2017-10-10python 實現(xiàn)求解字符串集的最長公共前綴方法
今天小編就為大家分享一篇python 實現(xiàn)求解字符串集的最長公共前綴方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07python logging.basicConfig不生效的原因及解決
今天小編就為大家分享一篇python logging.basicConfig不生效的原因及解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02