'How to get out of "std::thread::id" the same id as the "WinAPI thread-id" (on Windows)?

How to get out of std::thread::id the same id as the "Win API 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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1