1. 程式人生 > 程式設計 >Python守護程序實現過程詳解

Python守護程序實現過程詳解

這篇文章主要介紹了Python守護程序實現過程詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

如果你設定一個執行緒為守護執行緒,就表示你在說這個執行緒是不重要的,在程序退出的時候,不用等待這個執行緒退出。如果你的主執行緒在退出的時候,不用等待那些子執行緒完成,那就設定這些執行緒的daemon屬性。即線上程開始(thread.start())之前,呼叫setDeamon()函式,設定執行緒的daemon標誌。(thread.setDaemon(True))就表示這個執行緒“不重要”。

如果你想等待子執行緒完成再退出,那就什麼都不用做,或者顯示地呼叫thread.setDaemon(False),設定daemon的值為false。新的子執行緒會繼承父執行緒的daemon標誌。整個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()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。