本篇文章為大家展示了怎么在Python中實現一個守護進程,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
import time import threading def fun(): print "start fun" time.sleep(2) print "end fun" print "main thread" t1 = threading.Thread(target=fun,args=()) #t1.setDaemon(True) t1.start() time.sleep(1) print "main thread end"
結果:
main thread start fun main thread end end fun
結論:程序在等待子線程結束,才退出了。
設置:setDaemon 為True
import time import threading def fun(): print "start fun" time.sleep(2) print "end fun" print "main thread" t1 = threading.Thread(target=fun,args=()) t1.setDaemon(True) t1.start() time.sleep(1) print "main thread end"
結果:
main thread start fun main thread end
結論:程序在主線程結束后,直接退出了。 導致子線程沒有運行完。
守護進程可以通過調用isAlive(), 來監視其他線程是否是存活的。
如果死掉的話就重新建立一個工作線程,啟動起來(這里要注意不能使用原來的線程讓它start(),因為這個線程已經結束了,內存中的實例已經釋放掉了,所以使用這個方法會報錯)。
#coding=utf-8 import time from threading import Thread class ticker(Thread): def run(self): while True: print time.time() if (time.time() > 1470883000): break pass time.sleep(3) pass pass class moniter(Thread): def run(self): while True: global T if (T.isAlive()): print 't is alive' else : print 't is dead' T = ticker() T.start() print 'checking ' time.sleep(5) pass pass T = ticker() T.start() mo = moniter() mo.start()
上述內容就是怎么在Python中實現一個守護進程,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。