首页新闻招聘找找看知识库
  • 浏览:19 2017-06-14 11:54 来自 Zen_Garden

    最近需要用到Python3读写串口数据,需要用到技术涉及到:Python3,多线程,函数指针,Ctrl+C处理等,参考网上文章写成原型例子如下:

    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    
    import threading
    import time
    import sys,signalimport 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 ("退出主线程")

     

登录后才能评论,请先登录注册