python多线程不能执行中断信号
我现在做了一个计时器类,如果在时间没达到之前,能够按CTRL-C进行信号中断
程序代码如下:
#!/usr/bin/python
#FileName:timer.py
import threading
import time
import signal
def stopSignal(signum,frame):
global threadTimer
print "it is getting stopsignal"
threadTimer.stop()
signal.signal(signal.SIGINT,stopSignal)
class Timer(threading.Thread):
def __init__(self,threadName,interval,startTime,sharedObject):
threading.Thread.__init__(self,name=threadName)
self.__interval=interval
self.sharedObject=sharedObject
self.activeStatus=False
self.__startTime=startTime
def run(self):
self.activeStatus=self.sharedObject.getActive()
while self.activeStatus:
now=time.localtime(time.time())
compareTime=time.strftime("%H:%M",now)
if compareTime==self.__startTime:
print "The function is starting"
self.sharedObject.setActive(False)
self.activeStatus=self.sharedObject.getActive()
else:
print "The function is waiting"
time.sleep(self.__interval)
print "The thread is stopped"
def stop(self):
self.sharedObject.setActive(False)
self.activeStatus=self.sharedObject.getActive()
class SynchoronizedActive:
def __init__(self):
self.active=True
self.threadCondition=threading.Condition()
def setActive(self,boolean):
self.threadCondition.acquire()
self.active=boolean
self.threadCondition.notify()
self.threadCondition.release()
def getActive(self):
self.threadCondition.acquire()
tempResult=self.active
self.threadCondition.notify()
self.threadCondition.release()
return tempResult
theadActive=SynchoronizedActive()
threadTimer=Timer('threadTimer',20,'10:00',theadActive)
threadTimer.start()
threadTimer.join()
print "The program is end"
如果中途按CTRL-C,程序不会停止,等到程序运行结束后
结果如下;
>>>
The function is waiting
The function is waiting
The function is waiting
The function is waiting
The function is waiting
The function is starting
The thread is stopped
it is getting stopsignal
The program is end
这说明程序只能等到线程结束后才接受到了中断信号。因为如果他在中途接受中断信号至少会打印
it is getting stopsignal
请高手帮忙看下。