Question or problem about Python programming:
I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message.
I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?
How to solve the problem:
%(thread)d : Thread ID (if available).
%(threadName)s : Thread name (if available).
and set up your default handler with it:
thread.get_ident() function returns a long integer on Linux. It’s 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)
This functionality is now supported by Python 3.8+ 🙂
You can get the ident of the current running thread. The ident could be reused for other threads, if the current thread ends.
When you crate an instance of Thread, a name is given implicit to the thread, which is the pattern: Thread-number
The name has no meaning and the name don’t have to be unique. The ident of all running threads is unique.
import threading def worker(): print(threading.current_thread().name) print(threading.get_ident()) threading.Thread(target=worker).start() threading.Thread(target=worker, name='foo').start()
The function threading.current_thread() returns the current running thread. This object holds the whole information of the thread.