Python - 守護執行緒



在 Python 中,守護執行緒用於執行對程式操作不重要的後臺任務。它們允許您在後臺執行任務,而無需擔心跟蹤它們。

Python 提供兩種型別的執行緒:非守護執行緒和守護執行緒。預設情況下,執行緒是非守護執行緒。本教程將結合相關的示例,詳細解釋 Python 程式設計中的守護執行緒。

守護執行緒概述

有時,需要在後臺執行任務。一種特殊的執行緒用於後臺任務,稱為守護執行緒。換句話說,守護執行緒在後臺執行任務。這些執行緒處理非關鍵任務,這些任務可能對應用程式有用,但如果它們失敗或在操作中途被取消,也不會妨礙應用程式。

此外,守護執行緒無法控制其何時終止。一旦所有非守護執行緒完成,程式將終止,即使此時仍有守護執行緒正在執行。

守護執行緒與非守護執行緒的區別

守護執行緒 非守護執行緒
如果只有守護執行緒正在執行(或者沒有執行緒正在執行),則程序將退出。 如果至少有一個非守護執行緒正在執行,則程序將不會退出。
守護執行緒用於後臺任務。 非守護執行緒用於關鍵任務。
守護執行緒會被突然終止。 非守護執行緒會執行到完成。

守護執行緒可以執行以下任務:

  • 建立在後臺儲存日誌資訊的 檔案。

  • 在後臺執行網路抓取。

  • 自動將資料儲存到後臺的資料庫中。

在 Python 中建立守護執行緒

要建立守護執行緒,需要將Thread建構函式的daemon屬性設定為 True。

t1=threading.Thread(daemon=True)

預設情況下,daemon屬性設定為 None,如果將其更改為非 None,則 daemon 將明確設定執行緒是否為守護執行緒。

示例

請檢視以下示例,以建立守護執行緒並使用daemon屬性檢查執行緒是否為守護執行緒。

import threading 
from time import sleep

# function to be executed in a new thread
def run():
   # get the current thread
   thread = threading.current_thread()
   # is it a daemon thread?
   print(f'Daemon thread: {thread.daemon}')

# Create a new thread and set it as daemon
thread = threading.Thread(target=run, daemon=True)

# start the thread
thread.start()

print('Is Main Thread is Daemon thread:', threading.current_thread().daemon)

# Block for a short time to allow the daemon thread to run
sleep(0.5)

它將產生以下輸出

Daemon thread: True
Is Main Thread is Daemon thread: False

如果在主執行緒中建立執行緒物件沒有任何引數,則建立的執行緒將是非守護執行緒,因為主執行緒不是守護執行緒。因此,在主執行緒中建立的所有執行緒預設為非守護執行緒。但是,我們可以透過在啟動執行緒之前(也就是在呼叫start()方法之前)使用Thread.daemon屬性將daemon屬性更改為True

示例

這是一個示例:

import threading 
from time import sleep

# function to be executed in a new thread
def run():
   # get the current thread
   thread = threading.current_thread()
   # is it a daemon thread?
   print(f'Daemon thread: {thread.daemon}')

# Create a new thread  
thread = threading.Thread(target=run)

# Using the daemon property set the thread as daemon before starting the thread
thread.daemon = True

# start the thread
thread.start()

print('Is Main Thread is Daemon thread:', threading.current_thread().daemon)

# Block for a short time to allow the daemon thread to run
sleep(0.5)

執行上述程式後,我們將得到以下輸出:

Daemon thread: True
Is Main Thread is Daemon thread: False

管理守護執行緒屬性

如果嘗試在啟動執行緒後設置其守護程序狀態,則會引發RuntimeError。

示例

這是一個演示在嘗試啟動執行緒後設置其守護程序狀態時如何引發RuntimeError 的另一個示例。

from time import sleep
from threading import current_thread
from threading import Thread

# function to be executed in a new thread
def run():
   # get the current thread
   thread = current_thread()
   # is it a daemon thread?
   print(f'Daemon thread: {thread.daemon}')
   thread.daemon = True
   
# create a new thread
thread = Thread(target=run)

# start the new thread
thread.start()

# block for a 0.5 sec for daemon thread to run
sleep(0.5)

它將產生以下輸出

Daemon thread: False
Exception in thread Thread-1 (run):
Traceback (most recent call last):
   . . . .
   . . . .
    thread.daemon = True
  File "/usr/lib/python3.10/threading.py", line 1203, in daemon
    raise RuntimeError("cannot set daemon status of active thread")
RuntimeError: cannot set daemon status of active thread
廣告