Is getting the thread ID expensive in terms of per

2020-03-24 06:26发布

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.

3条回答
甜甜的少女心
2楼-- · 2020-03-24 06:44

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.

查看更多
爷的心禁止访问
4楼-- · 2020-03-24 06:53

According to MSDN (DevDiv#1039430), prior to VS2015

this_thread::get_id() was unnecessarily slow

Just how slow they don't say.

查看更多
登录 后发表回答