Python thread daemon property
我对将线程设置为守护进程意味着什么有点困惑。文件上说:
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.
我不知道是什么使它不同于普通的线。这是说这个计划永远不会结束吗?
1 2 3 4 5 | def threadfunc(): while True: time.sleep(1) threading.Thread(target=threadfunc).start() |
即使主线程完成了它的执行。同时
1 2 3 4 5 6 7 | def threadfunc(): while True: time.sleep(1) th = threading.Thread(target=threadfunc) th.daemon = True th.start() |
会立即完成吗?
我之所以这样问是因为在我的主线程中,我调用了sys.exit(),而进程挂起,而我的其他线程正在运行,正如我看到的日志一样。这与使用活动线程调用sys.exit()有什么关系吗?
Is this saying that this program won't ever finish?
是的,那个节目不会结束,就试试看。
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?
是的,即使是
设置
1 | th.daemon = True #set this thread as a Daemon Thread |
您可以将守护进程中的线程视为服务,这意味着它将在计算机后台运行,执行不同的任务,如索引文件、解析XML、检索新闻等,以及任何运行时间较长的过程。
您的主线程将完成,您的守护进程仍将在后台运行,这就是您的程序aka main thread完成的原因,如果您只需要放置一个无限循环,您将看到您的线程仍在运行。守护进程线程的一个例子是垃圾收集。