【问题标题】:Equivalent of thread.interrupt_main() in Python 3等效于 Python 3 中的 thread.interrupt_main()
【发布时间】:2018-10-30 12:25:58
【问题描述】:

在 Python 2 中有一个函数 thread.interrupt_main(),当从子线程调用时,它会在主线程中引发 KeyboardInterrupt 异常。

这也可以通过 Python 3 中的_thread.interrupt_main() 获得,但它是一个低级“支持模块”,主要用于其他标准模块。

在 Python 3 中实现这一点的现代方式是什么,大概是通过 threading 模块(如果有的话)?

【问题讨论】:

    标签: python python-3.x multithreading python-multithreading keyboardinterrupt


    【解决方案1】:

    手动引发异常有点低级,因此如果您认为必须这样做,只需使用 _thread.interrupt_main(),因为这是您要求的等价物(threading 模块本身不提供此功能)。

    不过,可能有一种更优雅的方式来实现您的最终目标。也许设置和检查标志就足够了,或者使用@RFmyD 已经建议的threading.Event,或者使用通过queue.Queue 传递的消息。这取决于您的具体设置。

    【讨论】:

    • 感谢_thread 的提示。不确定OP,但在我的情况下,我运行一个线程来监视一个进程是否应该运行,然后进程在主线程中运行(不管监视器实现如何),所以除了使用interrupt_main来杀死主进程之外我找不到任何其他方法
    【解决方案2】:

    您可能想查看 threading.Event 模块。

    【讨论】:

    • 嗨@RFmyD。请注意,这并不能提供问题的答案。一旦您拥有足够的声誉,您就可以对任何帖子发表评论 - 来自评论
    • @toti08 我认为这是一个有效的答案,而不是评论。评论有助于改进问题,在这种情况下,所指出的是一个可能的解决方案。
    【解决方案3】:

    如果您需要一种方法让线程停止执行整个程序,这就是我使用threading.Event 的方法:

    def start():
        """
        This runs in the main thread and starts a sub thread
        """
        
        stop_event = threading.Event()
        check_stop_thread = threading.Thread(
            target=check_stop_signal, args=(stop_event), daemon=True
        )
        check_stop_thread.start()
        # If check_stop_thread sets the check_stop_signal, sys.exit() is executed here in the main thread.
        # Since the sub thread is a daemon, it will be terminated as well.
        stop_event.wait()
        logging.debug("Threading stop event set, calling sys.exit()...")
        sys.exit()
    
    
    
    
    def check_stop_signal(stop_event):
        """
        Checks continuously (every 0.1 s) if a "stop" flag has been set in the database.
        Needs to run in its own thread.
        """
        while True:
            if io.check_stop():
                logger.info("Program was aborted by user.")
                logging.debug("Setting threading stop event...")
                stop_event.set()
                break
            sleep(0.1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多