- 论坛徽章:
- 0
|
ghostwwl 曾经发过一个精确控制子线程的代码,但是我没看懂,望高手指导,谢谢
代码引自 http://bbs.chinaunix.net/thread-3612044-1-1.html
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#****************************************************
# FileName: GThread.py
# Author: ghostwwl
# Note:
# 2008.10 add states and add Class_Timer
#****************************************************
import time
import threading
from timeit import default_timer
__author__ = "ghostwwl (ghostwwl@gmail.com)"
__version__ = "1.0"
#-------------------------------------------------------------------------------
class Thread_Control(object):
'''The Control Class'''
def __init__(self):
self.ControlEvent = threading.Event()
self.ControlEvent.set()
self.TimeOut = None
self.Terminated = False
self.CStateInfo = {-1:'STOP', 0:'READY', 1:'RUNNING', 2:'PAUSE'}
self.CSTATES = 0
def stop(self):
self.CSTATES = -1
print 'WARNING %s] Stopping Thread %-30s [ OK ]' % (time.strftime("%Y-%m-%d %H:%M:%S"),
self.getName())
self.Terminated = True
def pause(self, TimeOut = None):
self.TimeOut = TimeOut
self.ControlEvent.clear()
self.CSTATES = 2
def restore(self):
self.ControlEvent.set()
#-------------------------------------------------------------------------------
class mythread(threading.Thread, Thread_Control):
'''
BaseThread Class With Control Method[stop, pause, restore]
time dilution of precision about 1 millisecond
thread state {-1:'STOP', 0:'READY', 1:'RUNNING', 2:'PAUSE'}
'''
def __init__(self, owner, ThreadName, TimeSpacing=0, TimeDelay = 0):
'''
__init__(self, owner, ThreadName, TimeSpacing=0)
owner The Thread Owner
ThreadName The Thread Name
TimeSpacing Run TimeSpacing
TimeDelay The Thread Start TimeDelay
'''
self.owner = owner
self.TimeSpacing = TimeSpacing #任务多长时间执行一次
self.TimeDelay = TimeDelay
Thread_Control.__init__(self)
threading.Thread.__init__(self, name = ThreadName)
self.setDaemon(1)
def run(self):
'''
This While loop stop until Terminated
This Object Has sotp, pause(timeout = None) and restore method
'''
if self.TimeDelay != 0:
TSTART = self.TimeDelay
else:
TSTART = 0
while 1:
try:
#这里是线程的停止处理
if self.Terminated:
break
#这里是线程的暂停处理
if self.TimeOut is not None:
#带有暂停超时的处理
self.ControlEvent.wait(self.TimeOut)
self.TimeOut = None
self.ControlEvent.set()
else:
#不带超时 那么必须等到线程恢复
self.ControlEvent.wait()
CUR_TIMING = default_timer()
if CUR_TIMING - TSTART > self.TimeSpacing:
TSTART = CUR_TIMING
#这个才是我们的工作函数
self.CSTATES = 1
self.handle()
time.sleep(0.001) #暂停1毫秒 防止空跑占用过高cpu
except Exception, e:
print "ERROR %s] %s Error: %s" % (time.strftime("%H:%M:%S"), self.getName(), str(e))
def handle(self):
'''The Real Work Function'''
pass
def getstate(self):
'''check the thread state'''
return self.CSTATES
def getstatemsg(self):
return self.CStateInfo[self.CSTATES] |
|