- 论坛徽章:
- 0
|
怎么没人回答我
#!/usr/bin/python
#FileName:timer.py
import threading
import time
import signal
class Timer(threading.Thread):
def __init__(self,threadName,interval,startTime,sharedObject):
threading.Thread.__init__(self,name=threadName)
self.__interval=interval
self.sharedObject=sharedObject
self.__startTime=startTime
def run(self):
getStatus=self.sharedObject.getActive()
while getStatus:
now=time.localtime(time.time())
compareTime=time.strftime("%H:%M",now)
if compareTime==self.__startTime:
print "The function is starting\n"
self.sharedObject.setActive(False)
getStatus=self.sharedObject.getActive()
else:
print "The function is waiting\n"
print self.getName(),"done sleeping\n"
time.sleep(self.__interval)
getStatus=self.sharedObject.getActive()
print "The thread is stopped"
def stop(self):
self.sharedObject.setActive(False)
getStatus=self.sharedObject.getActive()
class SynchoronizedActive:
def __init__(self):
self.activeStatus=True
self.threadCondition=threading.Condition()
def setActive(self,boolean):
self.threadCondition.acquire()
self.activeStatus=boolean
self.threadCondition.notify()
self.threadCondition.release()
def getActive(self):
self.threadCondition.acquire()
tempResult=self.activeStatus
self.threadCondition.notify()
self.threadCondition.release()
return tempResult
class getCtrlThread(threading.Thread):
def __init__(self,threadName,interval,sharedObject):
threading.Thread.__init__(self,name=threadName)
self.__interval=interval
self.sharedObject=sharedObject
signal.signal(signal.SIGINT,self.stopSignal)
self.ctrlStop=True
def run(self):
while self.ctrlStop:
print self.getName(),"done sleeping\n"
time.sleep(self.__interval)
def stopSignal(self,signum,frame):
print "it is getting stopsignal\n"
self.sharedObject.setActive(False)
self.ctrlStop=False
theadActive=SynchoronizedActive()
threadTimer=Timer('threadTimer',4,'16:39',theadActive)
threadGetCtrl=getCtrlThread('threadgetCtrl',4,theadActive)
threadTimer.start()
threadGetCtrl.start()
print "return the mainthread\n"
time.sleep(4)
print "return the mainthread\n"
threadTimer.join()
threadGetCtrl.join()
print "The program is end"
这里如果我在程序运行开始的时候可以执行中断,过了几秒后在按ctrl-c就无效了。所有中断只能在
threadGetCtrl.join()语句执行之前发生。不然完全等待子线程运行。所有中断都失去效了。
请问斑竹怎样解决。 |
|