我将python线程设置为守护程序有什么区别 [英] What difference it makes when I set python thread as a Daemon

查看:105
本文介绍了我将python线程设置为守护程序有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用thread.setDaemon(True)将python线程设置为守护程序时,有什么不同?

What difference makes it when I set a python thread as a daemon, using thread.setDaemon(True)?

推荐答案

守护程序线程不会阻止应用程序退出.当所有非守护进程线程(包括主线程)完成时,程序结束.

A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.

因此,通常,如果您在后台执行某项操作,则可能需要将该线程设置为守护程序,这样您就不必在退出应用程序之前显式地使该线程的函数返回.

So generally, if you're doing something in the background, you might want to set the thread as daemon so you don't have to explicitly have that thread's function return before the app can exit.

例如,如果您正在编写GUI应用程序,并且用户关闭了主窗口,则该程序应退出.但是,如果周围有非守护进程线程挂起,则不会.

For example, if you are writing a GUI application and the user closes the main window, the program should quit. But if you have non-daemon threads hanging around, it won't.

从文档中: http://docs.python.org/library/threading.html#threading.Thread.daemon

其初始值继承自 创建线程;主线程 不是守护进程线程,因此 主线程中创建的所有线程 默认为daemon = False.

Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

整个Python程序在以下情况下退出 没有活动的非守护进程线程.

The entire Python program exits when no alive non-daemon threads are left.

这篇关于我将python线程设置为守护程序有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆