python 如何設置守護進程
上一篇文章 介紹 join 在多進程中的作用,本文繼續學習設置守護進程的對程序的影響。(Python大??梢岳@行)
我們通過兩個例子說明
# 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 #設置子進程p1為守護線程 p1.start() p2.start() print now() + ’ Process end .’
結果顯示
啟動了子進程 Run child process func_1 但是沒有 func_1 的結束提示。隨著主進程的結束而結束。
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 #設置子進程p2為守護線程 p1.start() p2.start() print now() + ’ Process end .’
結果顯示
啟動了子進程func_1,而func_2 沒有啟動便隨著主進程的結束而結束。
總結
對于進程或者子線程設置join() 意味著在子進程或者子線程結束運行之前,當前程序必須等待。當我們在程序中運行一個主進程(主線程),然后有創建多個子線程。主線程和子線程各自執行。當主線程想要退出程序時會檢查子線程是否結束。如果我們設置deamon屬性為True ,不管子線程是否結束,都會和主線程一起結束。
-The End-
以上就是python 如何設置守護進程的詳細內容,更多關于python 守護進程的資料請關注好吧啦網其它相關文章!
相關文章:
