Home > OS >  How to get out of "std::thread::id" the same id as the "WinAPI thread-id" (on Wi
How to get out of "std::thread::id" the same id as the "WinAPI thread-id" (on Wi

Time:05-18

How to get size_t value out of std::thread::id on Windows?

The thread-id is 9120 (id and this_id). I tried a few ANSI C ways, but they resulted in a different id:

image

Code:

int main()
{
    // Win API:

    const auto id = Concurrency::details::platform::GetCurrentThreadId(); // OK

    // ANSI C  :

    const std::thread::id this_id = std::this_thread::get_id(); // OK (but internal only: _id)

    constexpr std::hash<std::thread::id> myHashObject{};
    const auto threadId1 = myHashObject(std::this_thread::get_id());

    const auto threadId2 = std::hash<std::thread::id>{}(std::this_thread::get_id());

    const auto threadId3 = std::hash<std::thread::id>()(std::this_thread::get_id());
}

Update:

@Chnossos suggestion works as expected:

image

CodePudding user response:

You shouldn't rely on the format or value (see comments below). That being said, you can play with the operator<<:

#include <iostream>
#include <sstream>
#include <thread>

int main()
{
    std::stringstream ss;
    ss << std::this_thread::get_id();
    
    std::size_t sz;
    ss >> sz;

    std::cout << std::this_thread::get_id() << " vs. " << sz << std::endl;
}

Try it online

Output is not portable and there are no guarantees around the conversion or format of the conversion. Do not use this in production code.

  • Related