【问题标题】:How to terminate threads in python on raspberry pi 3?如何在树莓派 3 上终止 python 中的线程?
【发布时间】:2017-05-26 14:29:41
【问题描述】:

问题比较简单,只是我没找到 用谷歌搜索来回答:

  1. 如何在python中终止线程
  2. 如何在线程等中使用键盘输入结束 while 循环

所以程序的格式是这样的:

import everything necessary

def readingsomething():
      DOING SOME WORK in a infinite while loop and sleep for 1 sec

def readingsomeotherthing():
     DOING SOME WORK  in a infinite while loop and sleep for 2 sec

thread1 = thread.thread(target = readingsomething)

thread2 = thread.thread(target = readingsomeotherthing)

try:     
    thread1.start()
    thread2.start() 

    thread1.join()
    thread2.join()  

except KeyboardInterrupt:

    save a file and sys.exit() 

所以当我运行程序时,一切都很顺利,除非我 按 ctrl + c 它不会按照keyboardInterrupt 终止

我正在丢失收集的数据,因为我无法保存它们。

我们将不胜感激任何建议和帮助。

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。发帖时请务必使用proper formatting,以便帮助您的人更容易阅读您的代码。
  • 请正确缩进您的代码 - 在您执行它时。究竟是什么问题?
  • 代码正在编译并执行,但它应该只按 ctrl+c 终止,但它不会停止并继续执行我认为这是由于函数中的睡眠命令造成的问题

标签: python multithreading


【解决方案1】:

您可以使用同步队列Queue 作为管道向线程发送值。

【讨论】:

    【解决方案2】:

    目前还不清楚您要做什么。 你说的是循环,但我在你的代码中没有看到。

    另外,这样写,你会先等待thread1停止,然后等待thread2停止,确保它是你想要的。

    在这些“加入”调用中设置一个超时时间,否则会阻止监听异常:

    thread1.join()
    

    变成

    thread1.join(10)
    

    您可能需要考虑它对您的代码带来的变化。

    【讨论】:

    • 谢谢你的建议,我会试试的。循环在定义的函数中。
    【解决方案3】:

    工作 Python 3 示例:

    from threading import Thread, Event
    import time
    
    def readingsomething(stop):
        while not stop.isSet():
            print('readingsomething() running')
            time.sleep(1)
    
    def readingsomeotherthing(stop):
        while not stop.isSet():
            print('readingsomeotherthing() running')
            time.sleep(2)
    
    if __name__ == '__main__':
        stop = Event()
        thread1 = Thread(target=readingsomething, args=(stop,))
        thread2 = Thread(target=readingsomeotherthing, args=(stop,))
        thread1.start()
        thread2.start()
    
        try:
            thread1.join()
            thread2.join()
        except KeyboardInterrupt:
            print('catched KeyboardInterrupt')
            stop.set()
            #save the file
    
        print('EXIT __main__')
    

    用 Python:3.4.2 测试

    【讨论】:

    • 感谢您的建议,我会尝试一下。
    • 由于我使用的是 python3,key = input ('Press ctrl+c to terminate') 变成 key = eval(input('press ctl+c to terminate') 但我不断收到无效的语法错误在 c 上,我试图找出原因
    • 谢谢,我能够以类似的方式解决问题。
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2017-11-12
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    相关资源
    最近更新 更多