就性能而言,获取线程ID是否昂贵? [英] Is getting the thread ID expensive in terms of performance?

查看:92
本文介绍了就性能而言,获取线程ID是否昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我不控制的线程中访问线程ID(它在异步回调函数中,并且它从一组不同的线程中调用).

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).

我想知道就性能而言,访问线程ID是否昂贵?

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

我打算在Windows中使用boost::this_thread::get_id()GetCurrentThreadId().

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

为澄清起见,我需要准备一些本地缓存数组,以备数据从回调返回时使用,并且我正在计划以避免错误和锁定,以对每个线程使用本地缓存,并使用以下方法访问正确的缓存:线程ID. 另外,由于出现的数据总是具有不同的大小,因此我无法将其放入堆栈中,并且我想避免一直创建和删除堆数据.

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.

推荐答案

Windows将所有线程特定的信息存储在所谓的

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.

在x86窗口中,线程ID存储在FS:[0x24]中,这大概应该很便宜.将信息存储在线程本地存储中涉及一种额外的间接(我们从TEB获得TLS的地址),因此它与您的手动私有缓存基本相同-只需较少的工作即可.

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.

这篇关于就性能而言,获取线程ID是否昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆