Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of the thread by knowing the thread id?

I am working on a multithread traceback script, I am using the following code sample to retrieve the name of the thread, is there a nicer way to get the name of the thread out of the thread id?

for threadId, stack in sys._current_frames().items():
        tname = "None"
        for mthread in threading.enumerate():
            if mthread.ident == threadId:
                tname = mthread.name
like image 218
OHLÁLÁ Avatar asked Oct 22 '22 10:10

OHLÁLÁ


1 Answers

Not in the public interface of threading. Internally, threading maintains exactly the mapping you want, so you could write (at your own risk)

def thread_for_ident(ident):
    return threading._active.get(ident)

which will return None if there is no such thread. I don't think you're solution is actually too bad as long as there aren't many threads.

like image 71
Benjamin Peterson Avatar answered Oct 29 '22 02:10

Benjamin Peterson