Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 not size_t)

    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 :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading