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.
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.
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.
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.
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.
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.
Why not using thread local storage? http://www.boost.org/doc/libs/1_35_0/doc/html/thread/thread_local_storage.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With