python 如何設(shè)置守護(hù)進(jìn)程
上一篇文章 介紹 join 在多進(jìn)程中的作用,本文繼續(xù)學(xué)習(xí)設(shè)置守護(hù)進(jìn)程的對(duì)程序的影響。(Python大牛可以繞行)
我們通過(guò)兩個(gè)例子說(shuō)明
# encoding: utf-8'''author: [email protected]: 2019/7/30 11:20 AMfunc:'''from multiprocessing import Processimport osimport timedef now(): return str(time.strftime(’%Y-%m-%d %H:%M:%S’, time.localtime()))def func_1(name): print(now() + ’ Run child process %s ,pid is %s...’ % (name, os.getpid())) time.sleep(2) print(now() + ’ Stop child process %s ,pid is %s...’ % (name, os.getpid()))def func_2(name): print(now() + ’ Run child process %s , pid is %s...’ % (name, os.getpid())) time.sleep(4) print(now() + ’ hello world!’) print(now() + ’ Stop child process %s , pid is %s...’ % (name, os.getpid()))if __name__ == ’__main__’: print (’Parent process %s.’ % os.getpid()) p1 = Process(target=func_1, args=(’func_1’,)) p2 = Process(target=func_2, args=(’func_2’,)) print now() + ’ Process start.’ p1.daemon = True #設(shè)置子進(jìn)程p1為守護(hù)線程 p1.start() p2.start() print now() + ’ Process end .’
結(jié)果顯示
啟動(dòng)了子進(jìn)程 Run child process func_1 但是沒(méi)有 func_1 的結(jié)束提示。隨著主進(jìn)程的結(jié)束而結(jié)束。
if __name__ == ’__main__’: print (’Parent process %s.’ % os.getpid()) p1 = Process(target=func_1, args=(’func_1’,)) p2 = Process(target=func_2, args=(’func_2’,)) print now() + ’ Process start.’ p2.daemon = True #設(shè)置子進(jìn)程p2為守護(hù)線程 p1.start() p2.start() print now() + ’ Process end .’
結(jié)果顯示
啟動(dòng)了子進(jìn)程func_1,而func_2 沒(méi)有啟動(dòng)便隨著主進(jìn)程的結(jié)束而結(jié)束。
總結(jié)
對(duì)于進(jìn)程或者子線程設(shè)置join() 意味著在子進(jìn)程或者子線程結(jié)束運(yùn)行之前,當(dāng)前程序必須等待。當(dāng)我們?cè)诔绦蛑羞\(yùn)行一個(gè)主進(jìn)程(主線程),然后有創(chuàng)建多個(gè)子線程。主線程和子線程各自執(zhí)行。當(dāng)主線程想要退出程序時(shí)會(huì)檢查子線程是否結(jié)束。如果我們?cè)O(shè)置deamon屬性為T(mén)rue ,不管子線程是否結(jié)束,都會(huì)和主線程一起結(jié)束。
-The End-
以上就是python 如何設(shè)置守護(hù)進(jìn)程的詳細(xì)內(nèi)容,更多關(guān)于python 守護(hù)進(jìn)程的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解idea中web.xml默認(rèn)版本問(wèn)題解決2. ASP實(shí)現(xiàn)加法驗(yàn)證碼3. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算4. asp知識(shí)整理筆記4(問(wèn)答模式)5. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法6. JSP頁(yè)面實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能7. Python matplotlib 繪制雙Y軸曲線圖的示例代碼8. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)9. java 優(yōu)雅關(guān)閉線程池的方案10. jsp EL表達(dá)式詳解
