在 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)
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)
thread1.start()
thread1.join()
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)
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)
thread1.start()
thread1.join()
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)
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)
t1.start()
t1.join()
t2.start()
t2.join()
t3.name = 'custom_name'
t3.start()
t3.join()
print(threading.current_thread().name)
执行上述代码后,将会产生如下结果:
This Thread name is : My_thread
This Thread name is : Thread-1 (cube_number)
This Thread name is : custom_name
MainThread