Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getting the thread ID expensive in terms of performance?

I need to access the thread ID from threads that I don't control (it's in an asynchronous callback function, and it get called from a set of different threads).

I'd like to know if accessing the thread ID is expensive in terms of performance ?

I'm planning to use either boost::this_thread::get_id() or GetCurrentThreadId() from windows.

To clarify, I need to have some local cache array ready for when the data arrives from my callback, and I'm planning, to avoid errors and locking to use a local cache for each thread, and access the right cache using the thread id. Also because the data that comes is always of a different size, I can not put it in the stack, and I want to avoid creating and deleting heap data all the time.

like image 708
0x26res Avatar asked Oct 16 '12 07:10

0x26res


People also ask

Is process ID same as thread ID?

The thread ID of the initial (main) thread is the same as the process ID of the entire process. Thread IDs for subsequently created threads are distinct. They are allocated from the same numbering space as process IDs. Process IDs and thread IDs are sometimes also referred to collectively as task IDs.

How does a running thread find its thread ID?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.

Does a thread have an ID?

The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime.

Are thread IDs reused?

Because thread IDs can be reused without notice as threads are created and destroyed, this value is more reliable than the value returned by the GetCurrentThreadId function.


2 Answers

Windows stores all the thread specific information in the so called TEB. In x86 the fs register points to the start of this structure, in x64 it is the gs register.

In x86 windows the thread id is stored at FS:[0x24], which presumably should be rather cheap to access. Storing the information in thread local storage involves one extra indirection (we get the address of the TLS from the TEB), so it's basically the same as your handrolled private cache - just less work for you.

like image 167
Voo Avatar answered Nov 15 '22 03:11

Voo


Why not using thread local storage? http://www.boost.org/doc/libs/1_35_0/doc/html/thread/thread_local_storage.html

like image 38
kuperspb Avatar answered Nov 15 '22 05:11

kuperspb