python 如何設(shè)置守護(hù)進(jìn)程
上一篇文章 介紹 join 在多進(jìn)程中的作用,本文繼續(xù)學(xué)習(xí)設(shè)置守護(hù)進(jìn)程的對(duì)程序的影響。(Python大牛可以繞行)
我們通過兩個(gè)例子說明
# 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 但是沒有 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 沒有啟動(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. Intellij IDEA 2020.3 配置教程詳解2. Python操作Excel工作簿的示例代碼(*.xlsx)3. Ajax返回值類型與用法實(shí)例分析4. Python通過format函數(shù)格式化顯示值5. Ajax實(shí)現(xiàn)局部刷新的方法實(shí)例6. spring Retryable注解實(shí)現(xiàn)重試詳解7. 一篇文章弄清楚Ajax請(qǐng)求的五個(gè)步驟8. Vue router安裝及使用方法解析9. 使用 kind 和 Docker 啟動(dòng)本地的 Kubernetes環(huán)境10. asp知識(shí)整理筆記4(問答模式)
