Python之Monitor监控线程(干货)

在日常工作中常遇到这样的情况,我们需要一个监控线程用于随时的获得其他进程的任务请求,或者我们需要监视某些资源等的变化,一个高效的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.
'
13         while True:
14             if self.threadEvent.isSet():
15                 print 'Monitor is running...
'
16                 time.sleep(.1)
17             else:
18                 print 'Monitor is stopped.
'
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操作。

感谢阅读,希望能够帮到大家!

原文地址:https://www.cnblogs.com/berlin-sun/p/MonitorWithPython.html