当使用python的多线程时,我们有时候需要获取线程的名字,或者有需求需要区分各个线程。那么current_thread就是我们所需要的东西了。他能够获得线程的名字。实例如下:
一、获取线程的名字。
import threading
from threading import current_thread
def thrift_service():
print('the thread name is : ', current_thread().getName())
for i in range(10):
test_thread = threading.Thread(target=thrift_service)
test_thread.start()
获取线程的名字实际上并没有任何意义,有意义的事情是我们能够利用得到的线程的名字做什么操作
我在做的项目使用的是多线程,有一个函数在每次的调用中,所有线程中只需执行一次,所以,就可以使用所得到的线程名字进行判断,指定只需执行一次的函数在某个线程中执行。
二、判断是某一个线程时执行程序(当有需求是在所有线程中只执行一次时,可以使用该方法)
import threading
from threading import current_thread
def thrift_service():
if current_thread().getName() == 'Thread-1':
print('test just Thread-1 print, others thread not print')
for i in range(10):
test_thread = threading.Thread(target=thrift_service)
test_thread.start()
这是作者在项目中遇到的问题,在此记录一下,也希望能够帮组到有需要的你。如果文中有错误,还请指出。