簡體   English   中英

后台程序線程是否在后台運行?

[英]Does a daemon thread run in the background?

我對python中的daemonnon daemon線程感到非常困惑。 我讀到non daemon線程在Python中退出main thread退出!

但是在這里我讀到了在Java守護進程中線程在后台運行!

我已經閱讀了關於daemonnon daemon線程的關於stackoverflow的許多不同討論,但我仍然感到困惑!

您能否說明使用Python在后台運行哪個線程?

我認為您可能會混淆線程和進程。 正如您所說,線程和進程都提供並發執行序列,一件事“在后台運行”,而另一件事“在后台運行”。 它們之間的主要區別是線程共享內存而進程沒有共享內存。

您引用的問題涉及UNIX守護進程,通常是sshd類的后台進程。 這些與守護程序線程有點不同。

類似地,在Python和Java中,守護程序線程是不會阻止整個程序退出的線程。 當所有非守護程序線程運行完畢時,守護程序線程將被停止(可能會突然停止)。

TL; DR守護程序線程和非守護程序線程都將在Python中獨立並發執行(一定要確保您了解https://wiki.python.org/moin/GlobalInterpreterLock ),但不確定您的用例是什么,但是我認為非守護程序線程更常見,可能正是您想要的。

嘗試這個:

import threading
help(threading.Thread)

然后向下滾動到數據描述符的文檔,特別是“ daemon”標志。 在這里,您會找到以下信息:

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一樣使用術語“守護線程”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM