C++ Telltales part 1:
This is my first post of the C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series here!
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.
As many people were asking about this on Reddit, I created also an example application showing the Clang ThreadSanitizer. Here is a snippet of the main function:
And as you may know, this will produce a ThreadSanitizer warning as the counter is modified from two threads at the same time:
And as you can see — the IDs from the clang and from the get_thread_id function match perfectly. This also works with more than two threads just fine.
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. At least if the threads are restarted during the run of the program. Also Reddit conversation pointed out that using this kind of ids 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!
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.