简体   繁体   English

主程序结束时如何终止线程?

[英]How to terminate a thread when main program ends?

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

If you make your worker threads daemon threads, they will die when all your non-daemon threads (eg the main thread) have exited.如果你让你的工作线程守护线程,当你的所有非守护线程(例如主线程)退出时,它们就会死掉。

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

Check this question.检查这个问题。 The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?正确答案对如何以正确的方式终止线程有很好的解释: Is there any way to kill a Thread in Python?

To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting.要使线程在键盘中断信号 (ctrl+c) 上停止,您可以在退出之前捕获异常“KeyboardInterrupt”并进行清理。 Like this:像这样:

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

This way you can control what to do whenever the program is abruptly terminated.通过这种方式,您可以控制程序突然终止时的操作。

You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html您还可以使用内置的信号模块,让您设置信号处理程序(在您的特定情况下为 SIGINT 信号): http ://docs.python.org/library/signal.html

Try enabling the sub-thread as daemon-thread.尝试将子线程启用为守护线程。

For Instance:例如:

Recommended:推荐的:

from threading import Thread

t = Thread(target=desired_method)
t.daemon = True  # Dies when main thread (only non-daemon thread) exits.
t.start()

Inline:排队:

t = Thread(target=desired_method, daemon=True).start()

Old API:旧 API:

t.setDaemon(True)
t.start()

When your main thread terminates (eg Ctrl + C keystrokes), other threads will also be killed by the instructions above.当您的主线程终止时(例如Ctrl + C击键),其他线程也将被上述指令杀死。

Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt .使用 Python 标准库的atexit模块注册在主线程的任何合理“干净”终止时(在主线程上)调用的“终止”函数,包括未捕获的异常,例如KeyboardInterrupt Such termination functions may (though inevitably in the main thread!) call any stop function you require;这样的终止函数可能(尽管不可避免地在主线程中!)调用您需要的任何stop函数; together with the possibility of setting a thread as daemon , that gives you the tools to properly design the system functionality you need.连同将线程设置为daemon的可能性,这为您提供了正确设计所需系统功能的工具。

If you spawn a Thread like so - myThread = Thread(target = function) - and then do myThread.start(); myThread.join()如果你像这样生成一个线程 - myThread = Thread(target = function) - 然后执行myThread.start(); myThread.join() myThread.start(); myThread.join() . myThread.start(); myThread.join() When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join() call.启动 CTRL-C 时,主线程不会退出,因为它正在等待阻塞myThread.join()调用。 To fix this, simply put in a timeout on the .join() call.要解决这个问题,只需在 .join() 调用上设置一个超时。 The timeout can be as long as you wish.超时时间可以根据您的意愿进行。 If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True so all the threads exit when the main thread(non-daemon) exits.如果您希望它无限期地等待,只需设置一个非常长的超时时间,例如 99999。执行myThread.daemon = True也是一个好习惯,这样当主线程(非守护程序)退出时,所有线程都会退出。

Daemon threads are killed ungracefully so any finalizer instructions are not executed.守护线程被不优雅地杀死,因此不会执行任何终结器指令。 A possible solution is to check is main thread is alive instead of infinite loop.一种可能的解决方案是检查主线程是否处于活动状态而不是无限循环。

Eg for Python 3:例如对于 Python 3:

while threading.main_thread().isAlive():
    do.you.subthread.thing()
gracefully.close.the.thread()

See Check if the Main Thread is still alive from another thread .请参阅检查主线程是否仍然来自另一个线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM