python 如何設(shè)置守護(hù)進(jìn)程
上一篇文章 介紹 join 在多進(jìn)程中的作用,本文繼續(xù)學(xué)習(xí)設(shè)置守護(hù)進(jìn)程的對(duì)程序的影響。(Python大牛可以繞行)
我們通過(guò)兩個(gè)例子說(shuō)明
# encoding: utf-8'''author: yangyi@youzan.comtime: 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屬性為True ,不管子線程是否結(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. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. vue實(shí)現(xiàn)web在線聊天功能4. idea配置jdk的操作方法5. VMware中如何安裝Ubuntu6. Springboot 全局日期格式化處理的實(shí)現(xiàn)7. python 浮點(diǎn)數(shù)四舍五入需要注意的地方8. Docker容器如何更新打包并上傳到阿里云9. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法10. JAMon(Java Application Monitor)備忘記
