ETH官方钱包

前往
大廳
主題

C++11取得和轉換thread::id

Yang | 2023-06-24 16:07:33 | 巴幣 0 | 人氣 162

參考

和C#的
int Thread.CurrentThread.ManagedThreadId
有很大的不同,

C++11的thread::id是個物件,標準沒規定一定要能轉換成數字,但能轉換成字串(std::string)

但是目前在Win10/CentOS7/AIX7上測試過,字串似乎都被實作成以數字的形式呈現

可能是從1開始的不重複整數,可能是一串看不出規則,但不重複的長整數(長度>=15)

取得和轉換thread::id的程式碼記錄如下

class ThreadExtensions
{
    protected:
        static const std::string GetIDStr()
        {
            const std::thread::id& _tID = std::this_thread::get_id(); //取得目前的thread::id

            std::stringstream ss;
            ss << _tID;

            return ss.str(); //thread::id轉字串
        }

    public:
        static thread_local const std::string IDStr;
        static thread_local const long long IDValue;
};

thread_local const std::string ThreadExtensions::IDStr = ThreadExtensions::GetIDStr(); //取得目前的thread的ID(字串)
thread_local const long long ThreadExtensions::IDValue = std::stoll(ThreadExtensions::IDStr); //取得目前的thread的ID(數字)

std::stoll //字串(std::string)轉長整數(long long)

這段程式碼在Win10/CentOS7/AIX7編譯和測試過,目前將thread::id轉換成long long都沒問題

如果有其他平臺的thread::id不是數字,std::stoll應該會擲出std::invalid_argument的exception,但尚未做更多測試

230709補充:
雖然沒遇過thread::id不能轉成長整數(long long)的情況,但以防萬一,優化一下ThreadExtensions,

新增兩個錯誤碼列舉:
ExceptionInvalidArgument:不是數字
ExceptionOutOfRange:可能是數字但大於long long最大值

class ThreadExtensions
{
    protected:
        static const std::string GetIDStr()
        {
            const std::thread::id& _tID = std::this_thread::get_id();

            std::stringstream ss;
            ss << _tID;

            return ss.str();
        }

        static const long long GetIDValue(const std::string& id)
        {
            try
            {
                // id = "asdf1234zxcv";
                return std::stoll(id);
            }
            catch (const std::invalid_argument)
            {
                return ExceptionInvalidArgument;
            }
            catch (const std::out_of_range)
            {
                return ExceptionOutOfRange;
            }
        }

    public:
        static constexpr int ExceptionInvalidArgument = -1; //不是數字
        static constexpr int ExceptionOutOfRange = -2; //可能是數字但大於long long最大值

        static thread_local const std::string IDStr;
        static thread_local const long long IDValue;
};

thread_local const std::string ThreadExtensions::IDStr = ThreadExtensions::GetIDStr();
thread_local const long long ThreadExtensions::IDValue = ThreadExtensions::GetIDValue(ThreadExtensions::IDStr);
送禮物贊助創作者 !
0
留言

創作回應

更多創作