Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
This is my first post of the C++ Telltales series where I share some tips and tricks to work with C++. Hope you like it so I have reason to write another parts as well!
C++ offers a standard way to get the current thread id using std::this_thread::get_id() method. The method returns std::thread::id type which is unique identifier of the current thread. The std::thread::id can be printed out as it is, or through std::hash, but the output is not so nice and user friendly. If you have a multi-threaded application and you use some kind of logging functionality the following snippet might come in handy:
What it does is that it converts the std::thread::id to a single number and keeps the numbers in static map to have the the same number for the same threads. It becomes a lifesaver if you are using Clang ThreadSanitizer as the issues the sanitizer founds will be reported with the exactly same ids you achieve with this function. If you have to fix a threading issue, you can just check your logs for all the calls for threads that are causing it. Beautiful.
Using thread_local
It’s also possible to accomplish the same functionality without utilizing map or mutex by using thread_local variable instead:
Thanks for @obamurri in Reddit for pointing this out! Using this gives you the single number as unique identifier for the thread but unfortunately it does not match the ones sanitizer would give. Also reddit conversation pointed out that using this does not work well with tools like gdb and htop but if you are using the sanitizer it can make a big difference. To go around this you could log both of the ids.
And here it is as instaco.de image to have some cover photo for this story:
If you liked the story, please press the ❤ button below (did you know that you can give more than one clap). Also please feel free to share this story!
About me
I am Heikki Hellgren, Software Expert and technology enthusiast working at Elektrobit Automotive. My interests are in software construction, tools, automatic testing and all the new and cool stuff like AI and autonomous driving. You can follow me on Medium and Twitter and check out my website for more information.
Human-readable Thread ID was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.