multithreading – How to obtain a Thread id in Python?

multithreading – How to obtain a Thread id in Python?

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).

Using the logging module you can automatically add the current thread identifier in each log entry.
Just use one of these LogRecord mapping keys in your logger format string:

%(thread)d : Thread ID (if available).

%(threadName)s : Thread name (if available).

and set up your default handler with it:

logging.basicConfig(format=%(threadName)s:%(message)s)

multithreading – How to obtain a Thread id in Python?

The thread.get_ident() function returns a long integer on Linux. Its not really a thread id.

I use this method to really get the thread id on Linux:

import ctypes
libc = ctypes.cdll.LoadLibrary(libc.so.6)

# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186

def getThreadId():
   Returns OS thread id - Specific to Linux
   return libc.syscall(SYS_gettid)

Leave a Reply

Your email address will not be published. Required fields are marked *