Python daemon thread 解說

Last updated on  Sep 8, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read

閱讀 Python Threading 文件時,關於 Thread Objects 中有提到 Daemon Thread

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.

單看說明其實還不是特別清楚,可以用個範例實際幫助理解。

本文環境

  • Python 3.6.5

Thread v.s. Daemon Thread

談到 Daemon Thread 前必須認知一件事情。

一般的 Thread 都不是 Daemon Thread ,只有特別設置 Thread Object 的 daemon 屬性時, Thread 才會變成 Daemon Thread 。

假設 Python 主程式執行時,如果有 1 個一般的 thread 正在背景執行而且尚未結束,此時如果將 Python 主程式結束執行,這時候背景 Thread 仍會繼續執行,導致主程式看起來無法結束執行(但其實是因為此時 Thread 仍然在執行之中)。

以下範例模擬 1 個 Python 程式執行 Thread ,該 Thread 會在無窮迴圈內持續印出訊息,以模擬長時間背景執行的 Thread 。

# -*- coding: utf-8 -*-
import threading
import time


def target():
    ident = threading.get_ident()
    while True:
        print(f'Thread-{ident} says hi!')
        time.sleep(5)


thread = threading.Thread(target=target)

thread.start()
thread.join()

上述範例執行後,可以按 1 次 Crtl + c 試試,可以發現 Thread 仍然持續在執行,因為 Python 直譯器仍然在等背景的 Thread 執行結束才會正常結束(但範例程式的 Thread 執行的是無窮迴圈,所以永遠不會結束) 。

執行結果:

$ python thread.py
Thread-123145542037504 says hi!
Thread-123145542037504 says hi!
^CTraceback (most recent call last):
  File "pt.py", line 16, in <module>
    thread.join()
  File "/Users/.../anaconda3/lib/python3.6/threading.py", line 1056, in join
    self._wait_for_tstate_lock()
  File "/Users/.../anaconda3/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
Thread-123145542037504 says hi!
Thread-123145542037504 says hi!
Thread-123145542037504 says hi!
Thread-123145542037504 says hi!
...

而 Daemon Thread 與一般 Thread 不同的地方在於,背景執行的 Daemon Thread 在主程式被結束執行時,也會一同地被暴力結束執行。

以下範例程式,設定了 daemon=True 以啟用 Daemon Thread 。同樣可以執行之後按下 Ctrl + c 試圖結束程式的執行,接著就能夠發現 Daemon Thread 並沒有持續執行,而是被一併結束執行。

# -*- coding: utf-8 -*-
import threading
import time


def target():
    ident = threading.get_ident()
    while True:
        print(f'Thread-{ident} says hi!')
        time.sleep(5)


thread = threading.Thread(target=target, daemon=True)

thread.start()
thread.join()

執行結果:

$ python daemon-thread.py
Thread-123145475522560 says hi!
Thread-123145475522560 says hi!
^CTraceback (most recent call last):
  File "pt.py", line 16, in <module>
    thread.join()
  File "/Users/.../anaconda3/lib/python3.6/threading.py", line 1056, in join
    self._wait_for_tstate_lock()
  File "/Users/.../anaconda3/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
$ 

也由於是暴力中止 Daemon Thread 的執行,所以 Daemon Thread 如果正在進行寫檔、資料庫寫入等需要確保完整執行等任務時,就有可能被中斷導致資料完整性或是流程的完整性被破壞,因此不建議針對前述情境啟用 Daemon Thread 的選項。

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly.

以上就是 Daemon Thread 及 Thread 的區別,相信實際試著執行過一遍將會清楚許多。

References

https://docs.python.org/3/library/threading.html

對抗久坐職業傷害

研究指出每天增加 2 小時坐著的時間,會增加大腸癌、心臟疾病、肺癌的風險,也造成肩頸、腰背疼痛等常見問題。

然而對抗這些問題,卻只需要工作時定期休息跟伸展身體即可!

你想輕鬆改變現狀嗎?試試看我們的 PomodoRoll 番茄鐘吧! PomodoRoll 番茄鐘會根據你所設定的專注時間,定期建議你 1 項辦公族適用的伸展運動,幫助你打敗久坐所帶來的傷害!

追蹤新知

看完這篇文章了嗎?還意猶未盡的話,追蹤粉絲專頁吧!

我們每天至少分享 1 篇文章/新聞或者實用的軟體/工具,讓你輕鬆增廣見聞提升專業能力!如果你喜歡我們的文章,或是想了解更多特定主題的教學,歡迎到我們的粉絲專頁按讚、留言讓我們知道。你的鼓勵,是我們的原力!

贊助我們的創作

看完這篇文章了嗎? 休息一下,喝杯咖啡吧!

如果你覺得 MyApollo 有讓你獲得實用的資訊,希望能看到更多的技術分享,邀請你贊助我們一杯咖啡,讓我們有更多的動力與精力繼續提供高品質的文章,感謝你的支持!