技术要点:Python3,多线程,函数指针,Ctrl+C退出
#!/usr/bin/python3 # -*- coding:utf-8 -*- import threading import time import sys,signal import array #全局变量 exitFlag = 0 class LovoThread (threading.Thread): def __init__(self, Func, name, counter): threading.Thread.__init__(self) self.func = Func self.name = name self.counter = counter def run(self): print ("开始线程:" + self.name) self.func(self.name, self.counter, 1) print ("退出线程:" + self.name) def lovo_reader(threadName, counter, delay): global exitFlag while counter: if exitFlag: break time.sleep(delay) print ("%s: %s -- %d" % (threadName, time.ctime(time.time()), counter)) counter -= 1 def lovo_sender(threadName, counter, delay): global exitFlag while counter: if exitFlag: break time.sleep(delay) print ("%s: %s -- %d" % (threadName, time.ctime(time.time()), counter)) counter -= 1 def quit(signum, frame): global exitFlag print('中断执行.') exitFlag = 1 sys.exit() if __name__ == "__main__": # Ctrl + C 退出 signal.signal(signal.SIGINT, quit) signal.signal(signal.SIGTERM, quit) # 创建新线程 thread1 = LovoThread(lovo_reader, "Reader", 15) thread2 = LovoThread(lovo_sender, "Sender", 20) # 开启新线程 thread1.start() thread2.start() thread1.join() thread2.join() print ("退出主线程")