I am looking to convert integer types to string using std::to_string
, but I saw this paragraph:
std::to_string
relies onstd::locale
for formatting purposes, and therefore concurrent calls tostd::to_string
from multiple threads may result in partial serialization of calls.
But I couldn't find anything else on this topic, Google didn't come up wit anything, as did MSDN. I am using Visual Studio 2013 if it matters.
Is this thread safe? If so, how?
Obviously, no STL data structure is thread-safe. But at least, with std::vector for example, you can simply use mutexes to protect access to the vector.
None of the STL containers is thread safe, so std::set in particular isn't. In your case, the issue isn't even really thread safety, though: You simply share an object across multiple threads (fine) and modify it in one thread (fine as well).
std::sort could, in principle, use parallel execution when sorting elements of fundamental type (it wouldn't be observable whether it does), but not user-defined type (unless explicitly given permission via execution policy parameter, of course). The type's operator< may not be thread-safe.
The to_string() method takes a single integer variable or other data type and converts into the string.
std::to_string
behaves as if it calls sprintf
([string.conversions]/7), and the behavior of sprintf
depends on the global locale, which can be modified by setlocale
(or by std::locale::global
, which internally calls setlocale
).
The wording in [clocale.syn]/2 seems to imply that std::to_string
is thread safe, because it does not allow setlocale
to introduce a data race with std::to_string
or sprintf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With