为什么在 Python 中使用线程模块时 daeon 标志很有用?
给定如下简单脚本,为什么使用守护进程标志有用?也许这太简单了,但我知道守护线程通常是长时间运行的后台任务(正如 Raymond Hettinger 引用的那样,它们并不意味着要等待)。那么,如果我有一个我不等待的任务,并且只是启动一个非守护进程线程而不加入,那么这是伪守护进程吗?看起来功能是一样的。或者这更多的是记忆问题而不是处理逻辑问题?对于第二个问题,我实际上不确定这个脚本在守护进程与非守护进程方面消耗了多少资源
from threading import Thread
import time
import sys
def func():
for i in range(4):
print(f"Running Thread-{i}")
time.sleep(1)
t = Thread(target=func)
# t.daemon = True # nothing seems to change
t.start()
sys.exit()
Given a simple script as the following, why is using daemon flag useful? Maybe this is too simple, but I understand that daemon threads are generally long running background tasks (they are not meant to be waited for as quoted by Raymond Hettinger). So, if I have a task that I am not waiting for and simply start a non-daemon thread and not join, is that psuedo-daemon? It seems the functionality runs the same. Or is this more of a question of memory than processing logic? With the second question Im actually not sure how much resources this script consumes in the aspects of daemon vs non-daemon
from threading import Thread
import time
import sys
def func():
for i in range(4):
print(f"Running Thread-{i}")
time.sleep(1)
t = Thread(target=func)
# t.daemon = True # nothing seems to change
t.start()
sys.exit()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回来增加清晰度。我意识到当程序退出时,守护线程会显示出它们的真面目。把恶魔想象成恶魔,或者可鄙的、无意识的小卒子。 正如此处提到的,Python 会突然停止守护进程,无论它们是否已完成。因此,到目前为止,守护进程线程应该用于完成无关紧要的任务,以及等待/阻塞(即用于非守护进程的
.join()
) 但是存在警告(或者在本例中导致线条模糊的实现),如下所述守护进程==非守护进程 条件。
OR
我最初的帖子的混乱是由两部分组成的。我认为终止的程序(因此简单地包括 sys.exit )与“自行退出”的程序(上下文是关键,但守护程序与非守护程序的情况)之间可能存在差异,没有区别),而且事实是,通过“误导性”实现,您可以等待守护进程线程或突然杀死非守护进程。希望这可以帮助人们更多地了解 Python!
编辑:改进的解释
Coming back to add clarity. I realized that daemon threads show their true colors when a program is exiting. Think of daemons like demons, or despensable, mindless, little pawns. As mentioned here, Python will abruptly stop daemons, regardless if they have completed or not. So to this point, Daemon threads should be used for tasks where completion doesnt matter, and waiting/blocking (ie
.join()
for Non-Daemons. BUT there caveats (or in this case implementations that causes blurred lines) as described below.Daemon == Non-daemon on 2 conditions.
OR
My confusion leading to my original post was 2 parts. I was thinking there might be a difference between a terminated program ( hence trivially including
sys.exit
) vs one that "exits on its own" (context is key but the case of daemon vs non-daemon, no difference) and also that fact that yes, with "misleading" implementation, you can wait for daemon threads or abrupty kill non-daemons. Hopefully this helps someone understand Python a little more!Edit: Improved explanation