python 如何設(shè)置守護進程
上一篇文章 介紹 join 在多進程中的作用,本文繼續(xù)學習設(shè)置守護進程的對程序的影響。(Python大牛可以繞行)
我們通過兩個例子說明
# encoding: utf-8
"""
author: yangyi@youzan.com
time: 2019/7/30 11:20 AM
func:
"""
from multiprocessing import Process
import os
import time
def 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è)置子進程p1為守護線程
p1.start()
p2.start()
print now() + ' Process end .'
結(jié)果顯示

啟動了子進程 Run child process func_1 但是沒有 func_1 的結(jié)束提示。隨著主進程的結(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è)置子進程p2為守護線程
p1.start()
p2.start()
print now() + ' Process end .'
結(jié)果顯示

啟動了子進程func_1,而func_2 沒有啟動便隨著主進程的結(jié)束而結(jié)束。
總結(jié)
對于進程或者子線程設(shè)置join() 意味著在子進程或者子線程結(jié)束運行之前,當前程序必須等待。當我們在程序中運行一個主進程(主線程),然后有創(chuàng)建多個子線程。主線程和子線程各自執(zhí)行。當主線程想要退出程序時會檢查子線程是否結(jié)束。如果我們設(shè)置deamon屬性為True ,不管子線程是否結(jié)束,都會和主線程一起結(jié)束。
-The End-
以上就是python 如何設(shè)置守護進程的詳細內(nèi)容,更多關(guān)于python 守護進程的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中np.linalg.norm()用法實例總結(jié)
在線性代數(shù)中一個向量通過矩陣轉(zhuǎn)換成另一個向量時,原有向量的大小就是向量的范數(shù),這個變化過程的大小就是矩陣的范數(shù),下面這篇文章主要給大家介紹了關(guān)于Python中np.linalg.norm()用法的相關(guān)資料,需要的朋友可以參考下2022-07-07
在Python中操作列表之List.append()方法的使用
這篇文章主要介紹了在Python中操作列表之List.append()方法的使用,是Python入門學習中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
python GUI庫圖形界面開發(fā)之PyQt5控件QTableWidget詳細使用方法與屬性
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5控件QTableWidget詳細使用方法與屬性,需要的朋友可以參考下2020-02-02
Python反爬實戰(zhàn)掌握酷狗音樂排行榜加密規(guī)則
最新的酷狗音樂反爬來襲,本文介紹如何利用Python掌握酷狗排行榜加密規(guī)則,本章內(nèi)容只限學習,切勿用作其他用途?。。。?! 有需要的朋友可以借鑒參考下2021-10-10
pytorch 實現(xiàn)查看網(wǎng)絡(luò)中的參數(shù)
今天小編就為大家分享一篇pytorch 實現(xiàn)查看網(wǎng)絡(luò)中的參數(shù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python 實現(xiàn)以相同規(guī)律打亂多組數(shù)據(jù)
這篇文章主要介紹了python 實現(xiàn)以相同規(guī)律打亂多組數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
widows下安裝pycurl并利用pycurl請求https地址的方法
今天小編就為大家分享一篇widows下安裝pycurl并利用pycurl請求https地址的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10

