python线程监控配置文件_Python之Monitor监控线程

在日常工作中常遇到这样的情况,我们需要一个监控线程用于随时的获得其他进程的任务请求,或者我们需要监视某些资源等的变化,一个高效的Monitor程序如何使用python语言实现呢?为了解决上述问题,我将我所使用的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())

上述程序会循环60次,每次产生的随机数如果能够被5整除,如果已经有monitor线程在运行,则对计数器cnf进行++的操作,否则会启动一个monitor线程;如果产生的随机数能够被3整除而不能被5整除,则会terminate当前monitor线程,对cnf进行--操作!

程序所模拟的就是是否有任务请求,cnf用来记录当前请求的任务有那些,在我们的实际程序中,我们可以修改上述代码,增加一个等待队列用于记录请求但未得到调用的任务,而event.clear()之前我们则可以对得到请求申请的任务进行处理,当前任务结束调用之后再进行clear操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值