在日常工作中常遇到這樣的情況,我們需要一個(gè)監(jiān)控線程用于隨時(shí)的獲得其他進(jìn)程的任務(wù)請(qǐng)求,或者我們需要監(jiān)視某些資源等的變化,一個(gè)高效的Monitor程序如何使用python語言實(shí)現(xiàn)呢?為了解決上述問題,我將我所使用的Monitor程序和大家分享,見代碼
import threading
import random
import time
import sys
class MonitorThread(threading.Thread):
def __init__(self, event):
threading.Thread.__init__(self)
self.threadEvent = event
def run(self):
print 'Monitor is ready.\n'
while True:
if self.threadEvent.isSet():
print 'Monitor is running...\n'
time.sleep(.1)
else:
print 'Monitor is stopped.\n'
break
def main():
count = 60
cnf = 0
event = threading.Event()
while count >= 0:
print 'There are %s tasks in queue!' % str(cnf)
count -= 1
num = random.randint(1, 100)
if num%5 == 0:
if cnf == 0:
event.set()
t = MonitorThread(event)
t.start()
cnf += 1
elif num%3 == 0 and num%15 != 0:
if cnf >= 1:
event.clear()
time.sleep(2)
if cnf >= 1:
cnf -= 1
time.sleep(5)
if cnf >= 1:
event.clear()
if __name__ == '__main__':
sys.exit(main())
上述程序會(huì)循環(huán)60次,每次產(chǎn)生的隨機(jī)數(shù)如果能夠被5整除,如果已經(jīng)有monitor線程在運(yùn)行,則對(duì)計(jì)數(shù)器cnf進(jìn)行++的操作,否則會(huì)啟動(dòng)一個(gè)monitor線程;如果產(chǎn)生的隨機(jī)數(shù)能夠被3整除而不能被5整除,則會(huì)terminate當(dāng)前monitor線程,對(duì)cnf進(jìn)行--操作!
程序所模擬的就是是否有任務(wù)請(qǐng)求,cnf用來記錄當(dāng)前請(qǐng)求的任務(wù)有那些,在我們的實(shí)際程序中,我們可以修改上述代碼,增加一個(gè)等待隊(duì)列用于記錄請(qǐng)求但未得到調(diào)用的任務(wù),而event.clear()之前我們則可以對(duì)得到請(qǐng)求申請(qǐng)的任務(wù)進(jìn)行處理,當(dāng)前任務(wù)結(jié)束調(diào)用之后再進(jìn)行clear操作。