守护程序线程是否在后台运行?

时间:2015-06-13 23:16:16

标签: python multithreading

我对python中的daemonnon daemon线程非常困惑。我读到在non daemon退出Python时main thread线程退出!

here我读到Java守护程序线程在后台运行!

关于daemonnon daemon线程的stackoverflow,我已经阅读了很多不同的讨论,但我仍感到困惑!

你能否说明使用Python在后台运行哪个线程?

2 个答案:

答案 0 :(得分:1)

我认为你可能会混淆线程和进程。线程和进程都提供了并发执行序列,有一件事是“在后台运行”而另一件事是执行的,正如你所说的那样。它们之间的一个主要区别是线程具有共享内存,而进程则没有。

您引用的问题是指UNIX守护程序进程,它通常是后台进程,如sshd或其他东西。这些与守护程序线程略有不同。

在Python和java中类似地,守护程序线程是一个不会阻止整个程序退出的线程。当所有非守护程序线程都运行完毕后,守护程序线程将被停止(可能是突然)。

TL; DR守护进程和非守护进程线程将在Python中独立并同时执行(有点,确保你理解https://wiki.python.org/moin/GlobalInterpreterLock),不确定你的用例是什么,但我认为非守护进程线程是更常见,可能是你想要的。

答案 1 :(得分:1)

试试这个:

import threading
help(threading.Thread)

然后向下滚动到数据描述符的文档,特别是“守护进程”标志。在那里,你会发现这个信息:

daemon
   A boolean value indicating whether this thread is a daemon thread.

   This must be set before start() is called, otherwise RuntimeError is
   raised. 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.

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

特别是最后一句很重要,因为你所有的问题都是由你暗中回答的。另请注意,这与您的第一个声明相矛盾,即“主线程退出时非守护程序线程退出”。此外,其他语言的行为也不同,例如,您对Java的引用可能是正确的,但无法解释Python行为。检查文档,似乎Java完全像Python一样使用术语“守护程序线程”。