代码之家  ›  专栏  ›  技术社区  ›  facha

python:如何在主程序结束时终止线程

  •  66
  • facha  · 技术社区  · 15 年前

    如果在无限循环中有线程,有没有方法在主程序结束时终止它(例如,当我按下 Ctrl键 + C )?

    5 回复  |  直到 7 年前
        1
  •  38
  •   Community CDub    8 年前

    检查这个问题。正确的答案对如何正确终止线程有很好的解释: Is there any way to kill a Thread in Python?

    要使线程在键盘中断信号(ctrl+c)上停止,您可以捕获异常“keyboard interrupt”并在退出前清除。这样地:

    try:
        start_thread()  
    except (KeyboardInterrupt, SystemExit):
        cleanup_stop_thread()
        sys.exit()
    

    这样,当程序突然终止时,您就可以控制要做什么。

    您还可以使用内置的信号模块来设置信号处理程序(在特定情况下为sigint信号): http://docs.python.org/library/signal.html

        2
  •  80
  •   ʇsәɹoɈ    15 年前

    如果您使您的工作线程成为守护进程线程,那么当所有非守护进程线程(例如主线程)都退出时,它们将死亡。

    http://docs.python.org/library/threading.html#threading.Thread.daemon

        3
  •  12
  •   Alex Martelli    15 年前

    使用 atexit python标准库中的一个模块,用于注册在主线程的任何合理“干净”终止时(在主线程上)被调用的“终止”函数,包括未捕获的异常,例如 KeyboardInterrupt . 这样的终止函数可能(尽管在主线程中不可避免!)任意呼叫 stop 您需要的函数;以及将线程设置为 daemon ,这为您提供了适当设计所需系统功能的工具。

        4
  •  8
  •   Milean    12 年前

    如果你像这样产生一条线- myThread = Thread(target = function) -然后再做 myThread.start(); myThread.join() . 当启动ctrl-c时,主线程不会退出,因为它正在等待该阻塞 myThread.join() 打电话。要解决这个问题,只需在.join()调用上设置一个超时。超时时间可以任意长。如果您希望它无限期地等待,只需输入一个非常长的超时,比如99999。这也是很好的做法 myThread.daemon = True 所以当主线程(非守护进程)退出时,所有线程都会退出。

        5
  •  4
  •   Benyamin Jafari    7 年前

    尝试将子线程启用为守护进程线程。

    例如:

    from threading import Thread
    
    threaded = Thread(target=<your-method>)
    threaded.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.
    threaded.start()
    

    或(在一行中):

    from threading import Thread
    
    threaded = Thread(target=<your-method>, daemon=True).start()
    

    当主线程终止时(“例如,当我按下 Ctrl键 + C “)其他线程使用上述指令终止。