Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is operation of getting id of current thread time expensive? [duplicate]

I'm going to use id of current running thread in a very performance critical place in my code, so I should choose whether to cache that id somewhere or to call a method (gettid for unix-like systems and GetCurrentThreadId for windows) for getting it every time. So which is better? Is getting thread id a system call?

like image 996
Mihran Hovsepyan Avatar asked Feb 21 '13 16:02

Mihran Hovsepyan


People also ask

What thread ID is used for?

The thread ID is used by the operating system to identify processes and threads. The thread id is unique globally but the users can capture the thread handle of the process thread through this id.

Does a thread have an ID?

In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.


2 Answers

At least in Windows, GetCurrentThreadId() is quite cheap, and does not involve a system call. Basically it works out to:

int GetCurrentThreadId() { 
    _asm { 
        mov eax, fs:[18h]
        mov eax, [eax+24h]
    }
}

There could be a little benefit to caching the value in your own variable, but not a lot. The main benefit would probably be if you stored your variable along with other frequently used variables, which could improve locality (and therefore cache usage).

So, unless you're working on such a tight loop that the possibility of eliminating a memory fetch (or possibly two) is significant, you're unlikely to gain much by caching the value it returns.

like image 150
Jerry Coffin Avatar answered Nov 05 '22 15:11

Jerry Coffin


No, it is not an expensive call. It is a system call or similar, but far from an expensive one. Obviously, if you can cache the value in a simple variable then that would make it faster by a factor of 10.

But like all performance related queries, it's really down to your benchmarking. You can pretty easily set things up to use a single thread, call the function to get the thread ID, and do what you want to do. Measure how long it takes to run some test with that. Then replace the call for the thread ID with a constant value in the same range, and see how that works out.

like image 42
Mats Petersson Avatar answered Nov 05 '22 15:11

Mats Petersson