Python线程上daemon属性的含义 [英] Meaning of daemon property on Python Threads

查看:100
本文介绍了Python线程上daemon属性的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于将线程设置为守护程序意味着什么,我有些困惑.

I'm a little confused about what setting a thread to be a daemon means.

文档说:

可以将线程标记为守护程序" 线".这个标志的意义 是整个Python程序 仅当守护程序线程处于退出状态时退出 左边.初始值是继承的 从创建线程.该标志可以 通过daemon属性设置.

A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

我不确定是什么使它与普通线程有所不同.

I'm not sure what makes this different from a normal thread.

是说这个程序永远不会结束吗?

Is this saying that this program won't ever finish?

def threadfunc():
    while True:
        time.sleep(1)

threading.Thread(target=threadfunc).start()

即使主线程完成了执行.什么会立即完成?

Even though the main thread finishes it's execution. While will finish immediately?

def threadfunc():
    while True:
        time.sleep(1)

th = threading.Thread(target=threadfunc)
th.daemon = True
th.start()

我问是因为遇到这样的情况,在主线程中我正在调用sys.exit(),并且该进程只是挂起,而其他线程正在运行,因为我可以看到日志.

I ask because I have a situation where in my main thread I'm calling sys.exit(), and the process just hangs and my other threads are running as I can see the log.

这与在有活动线程的情况下调用sys.exit()有什么关系吗?

Does this have anything to do with sys.exit() being called with threads alive?

推荐答案

是说这个程序永远不会结束吗?

Is this saying that this program won't ever finish?

是的,该程序无法完成,只需尝试一下即可.

Yes, that program won't finish, just try it out.

我问是因为我有一种情况 在我的主线程中 sys.exit(),该过程只是挂起 和我的其他线程正在运行 可以看到日志.请问有 与sys.exit()有关 被线程激活而被调用?

I ask because I have a situation where in my main thread I'm calling sys.exit(), and the process just hangs and my other threads are running as I can see the log. Does this have anything to do with sys.exit() being called with threads alive?

是的,即使exit也不会停止其他线程,它只是在主线程中引发SystemExit.因此,尽管主线程将停止(就像在其他任何未处理的Exception上一样),所有其他非守护线程将继续工作.

Yes, even exit won't stop other threads, it simply raises SystemExit in the main thread. So while the main thread will stop (just like it does on any other unhandled Exception), all other non-daemonic threads will continue to work.

这篇关于Python线程上daemon属性的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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