32

How to typecast std::thread::id to string in C++? I am trying to typecast output generated by std::this_thread::get_id() to a string or char array.

2
  • what do you mean by "convert"? what do you want to do with the "converted" std::thread::id? Commented Oct 8, 2013 at 18:11
  • @Walter I want to log it for debug purpose Commented May 16, 2023 at 10:47

3 Answers 3

49
auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();
Sign up to request clarification or add additional context in comments.

Comments

19

Actually std::thread::id is printable using ostream (see this).

So you can do this:

#include <sstream>

std::ostringstream ss;

ss << std::this_thread::get_id();

std::string idstr = ss.str();

Comments

7

You may "convert" it to a small integer number useful for easy identification by humans:

std::size_t index(const std::thread::id id)
{
    static std::size_t nextindex = 0;
    static std::mutex my_mutex;
    static std::unordered_map<std::thread::id, std::size_t> ids;
    std::lock_guard<std::mutex> lock(my_mutex);
    auto iter = ids.find(id);
    if(iter == ids.end())
        return ids[id] = nextindex++;
    return iter->second
}

4 Comments

Not a strict answer to the question, but a very useful answer nonetheless!
What the purpose of these code? Index does not show "real" thread sequence number. It almost the same "useless text" but useless number.
It provides a unique id to the thread. Your "real thread sequence number" is less unique, since it is implementation dependent -- while most implementations use pthreads, that's not guaranteed, nor is the existence of a "real thread sequence number".
This is impressive, horrifying, and useful all at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.