Python - 執行緒命名



在 Python 中,執行緒命名涉及為執行緒物件分配一個字串作為識別符號。Python 中的執行緒名稱主要用於識別目的,不會影響執行緒的行為或語義。多個執行緒可以共享同一個名稱,並且可以線上程初始化期間或動態地指定名稱。

Python 中的執行緒命名提供了一種簡單的方法來識別和管理併發程式中的執行緒。透過分配有意義的名稱,使用者可以增強程式碼清晰度並輕鬆除錯複雜的多執行緒應用程式。

在 Python 中命名執行緒

當您使用threading.Thread()類建立執行緒時,您可以使用name引數指定其名稱。如果未提供,Python 會分配一個預設名稱,例如以下模式“Thread-N”,其中 N 是一個小十進位制數。或者,如果您指定了一個目標函式,則預設名稱格式變為“Thread-N (target_function_name)”。

示例

以下示例演示了使用threading.Thread()類為建立的執行緒分配自定義和預設名稱,並顯示名稱如何反映目標函式。

from threading import Thread
import threading
from time import sleep

def my_function_1(arg):
   print("This tread name is", threading.current_thread().name)

# Create thread objects
thread1 = Thread(target=my_function_1, name='My_thread', args=(2,))
thread2 = Thread(target=my_function_1, args=(3,))

print("This tread name is", threading.current_thread().name)

# Start the first thread and wait for 0.2 seconds
thread1.start()
thread1.join()

# Start the second thread and wait for it to complete
thread2.start()
thread2.join()

執行上述程式碼後,將產生以下結果:

This tread name is MainThread
This tread name is My_thread
This tread name is Thread-1 (my_function_1)

動態為 Python 執行緒分配名稱

您可以透過直接修改執行緒物件的 name 屬性來動態分配或更改執行緒的名稱。

示例

此示例演示瞭如何透過修改執行緒物件的name屬性來動態更改執行緒名稱。

from threading import Thread
import threading
from time import sleep

def my_function_1(arg):
   threading.current_thread().name = "custom_name"
   print("This tread name is", threading.current_thread().name)

# Create thread objects
thread1 = Thread(target=my_function_1, name='My_thread', args=(2,))
thread2 = Thread(target=my_function_1, args=(3,))

print("This tread name is", threading.current_thread().name)

# Start the first thread and wait for 0.2 seconds
thread1.start()
thread1.join()

# Start the second thread and wait for it to complete
thread2.start()
thread2.join()

執行上述程式碼後,將產生以下結果:

This tread name is MainThread
This tread name is custom_name
This tread name is custom_name

示例

執行緒可以初始化為自定義名稱,甚至可以在建立後重命名。此示例演示了建立具有自定義名稱的執行緒並在建立後修改執行緒的名稱。

import threading

def addition_of_numbers(x, y):
   print("This Thread name is :", threading.current_thread().name)
   result = x + y

def cube_number(i):
   result = i ** 3
   print("This Thread name is :", threading.current_thread().name)

def basic_function():
   print("This Thread name is :", threading.current_thread().name)

# Create threads with custom names
t1 = threading.Thread(target=addition_of_numbers, name='My_thread', args=(2, 4))
t2 = threading.Thread(target=cube_number, args=(4,))
t3 = threading.Thread(target=basic_function)

# Start and join threads
t1.start()
t1.join()

t2.start()
t2.join()

t3.name = 'custom_name'  # Assigning name after thread creation
t3.start()
t3.join()

print(threading.current_thread().name)  # Print main thread's name

執行後,上述程式碼將產生以下結果:

This Thread name is : My_thread
This Thread name is : Thread-1 (cube_number)
This Thread name is : custom_name
MainThread
廣告