在寫多線程時,因為某些需求,需要獲得 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
測試通過