在日常工作中常遇到這樣的情況,我們需要一個監控線程用於隨時的獲得其他進程的任務請求,或者我們需要監視某些資源等的變化,一個高效的Monitor程序如何使用python語言實現呢?為了解決上述問題,我將我所使用的Monitor程序和大家分享,見代碼:
1 import threading 2 import random 3 import time 4 import sys 5 6 class MonitorThread(threading.Thread): 7 def __init__(self, event): 8 threading.Thread.__init__(self) 9 self.threadEvent = event 10 11 def run(self): 12 print 'Monitor is ready.\n' 13 while True: 14 if self.threadEvent.isSet(): 15 print 'Monitor is running...\n' 16 time.sleep(.1) 17 else: 18 print 'Monitor is stopped.\n' 19 break 20 21 def main(): 22 count = 60 23 cnf = 0 24 event = threading.Event() 25 while count >= 0: 26 print 'There are %s tasks in queue!' % str(cnf) 27 count -= 1 28 num = random.randint(1, 100) 29 if num%5 == 0: 30 if cnf == 0: 31 event.set() 32 t = MonitorThread(event) 33 t.start() 34 cnf += 1 35 elif num%3 == 0 and num%15 != 0: 36 if cnf >= 1: 37 event.clear() 38 time.sleep(2) 39 if cnf >= 1: 40 cnf -= 1 41 time.sleep(5) 42 if cnf >= 1: 43 event.clear() 44 45 if __name__ == '__main__': 46 sys.exit(main())
上述程序會循環60次,每次產生的隨機數如果能夠被5整除,如果已經有monitor線程在運行,則對計數器cnf進行++的操作,否則會啟動一個monitor線程;如果產生的隨機數能夠被3整除而不能被5整除,則會terminate當前monitor線程,對cnf進行--操作!
程序所模擬的就是是否有任務請求,cnf用來記錄當前請求的任務有那些,在我們的實際程序中,我們可以修改上述代碼,增加一個等待隊列用於記錄請求但未得到調用的任務,而event.clear()之前我們則可以對得到請求申請的任務進行處理,當前任務結束調用之后再進行clear操作。
感謝閱讀,希望能夠幫到大家!
