對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)文章
python密碼學(xué)列置換密碼學(xué)習(xí)
這篇文章主要為大家介紹了python密碼學(xué)列置換密碼學(xué)習(xí)的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
Win10系統(tǒng)下Pytorch環(huán)境的搭建過程
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Win10系統(tǒng)Pytorch環(huán)境搭建過程展開,文中有非常詳細的介紹及圖文示例,需要的朋友可以參考下2021-06-06
用Python批量把文件復(fù)制到另一個文件夾的實現(xiàn)方法
這篇文章主要介紹了用Python批量把文件復(fù)制到另一個文件夾的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

