How get the thread id without system call? and does getting the system time takes less, more or the same as getting the thread id using a system call?

StackOverflow https://stackoverflow.com/questions/22427446

Question

I my application I have a log wrapper class and macros like LOG_DEBUG(message), LOG_ERROR(message) and so on. When I use for example LOG_DEBUG(message) it prints the time, the message and the letter D which stands for debug. What I would like to do is to add to the macro the functionality to print the thread id which executed the LOG command. At first I added syscall(SYS_gettid) to the log wrapper class, this works alright, my question is, can I do it without the system call?

I though about using thread local storage to store in user space the thread id in a map where its key is given by pthread_key_create, but I wanted to know if there is some other way which I didn't think of.

While trying to figure it out I noticed by using strace that in order to get the time I'm actually calling a system call and thus for each log I get a context switch. I can't think of of a way to circumvent this but I wanted to know if getting the thread id by system call take roughly less, more or about the same time as getting the system time.

Was it helpful?

Solution

Eventually, I used gcc implementation of thread local storage see this for more details.

I added a tid variable of pid_t type in the global scope but with __thread keyword in front. Inside the function that the thread executes, I assigned to tid its value by calling syscall(SYS_gettid). From that moment tid had the right value and from each thread you can access it directly as a global variable but it has its own copy for each thread. The last thing I had to do is to add tid to the LOG macros. This solves the issue completely and no complicated API of posix threads is required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top