如何从 "std::thread::id" 中取出与 "WinAPI thread-id" 相同的 id(在 Windows 上)?

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

如何退出 std::thread::id 与“Win API thread-id”相同的 ID(在 Windows 上)?

线程 ID 为 9120(idthis_id)。我尝试了几种 ANSI C++ 方法,但它们导致了不同的 ID:

代码:

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());
}

更新:

@Chnossos 建议按预期工作:

您不应依赖格式或值(请参阅下面的评论)。也就是说,您可以使用 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

输出不可移植,无法保证转换或转换格式。不要在生产代码中使用它。