Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a thread name in Python?

I'm trying to get the thread name test_thread with threading.current_thread().name between t.start() and t.join() as shown below:

import threading

def test():
    print("test")
                                  # Thread name                  
t = threading.Thread(target=test, name="test_thread")
t.start()
print(threading.current_thread().name) # Here
t.join()

But, I got MainThread instead of test_thread as shown below:

test
MainThread # Here

So, how can I get the thread name?

like image 968
Kai - Kazuya Ito Avatar asked Jul 04 '26 10:07

Kai - Kazuya Ito


1 Answers

You need to use threading.current_thread().name in test() as shown below:

import threading

def test():
    print("test")
    print(threading.current_thread().name) # Here
                                                              
t = threading.Thread(target=test, name="test_thread")
t.start()                         # Thread name
t.join()

Then, you can get test_thread instead of MainThread as shown below:

test
test_thread # Here

In addition, if you use t.name out of test() as shown below:

import threading

def test():
    print("test")
                                                              
t = threading.Thread(target=test, name="test_thread") # "threads" to "t" substitution
t.start()                              # Thread name
t.join()
print(t.name) # Here

You can get the thread name test_thread as shown below:

test
test_thread # Here
like image 73
Kai - Kazuya Ito Avatar answered Jul 05 '26 23:07

Kai - Kazuya Ito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!