从std::thread::id取得int值id

在写多线程时,因为某些需求,需要获得 std::this_thread::get_id() 的 std::thread::id 类型值转换为 unsigned int 类型值,并且与cout<<std::this_thread::get_id() 输出值一致

https://stackoverflow.com/questions/7432100/how-to-get-integer-thread-id-in-c11#

在 stackoverflow 参考了很多方法后尝试都不尽人意

最后跟入 std::thread::id 结构,如下

class id{
...
//其余皆为非虚函数
private:
      _Thrd_t _Thr;
}  

其中 _Thrd_t 结构定义如下

typedef struct
{    /* thread identifier for Win32 */
    void *_Hnd;    /* Win32 HANDLE */
    unsigned int _Id;
} _Thrd_imp_t;
typedef _Thrd_imp_t _Thrd_t;

其中,_Id 即为我们想取到的 unsigned int 值

于是灵光一闪,只有一个参数且没有虚函数表,利用强大的C++指针岂不是能够很简单很快速的获取到 private 值?

在线程中测试如下代码

std::thread::id tid = std::this_thread::get_id();
_Thrd_t t = *(_Thrd_t*)(char*)&tid ;
unsiged int nId = t._Id

测试通过

  

猜你喜欢

转载自www.cnblogs.com/yc-only-blog/p/9178935.html
id