Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::to_string thread safe?

I am looking to convert integer types to string using std::to_string, but I saw this paragraph:

std::to_string relies on std::locale for formatting purposes, and therefore concurrent calls to std::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?

like image 636
roybj Avatar asked Jul 18 '17 19:07

roybj


People also ask

Is STD string thread-safe?

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.

Is std :: set insert thread-safe?

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).

Is std :: sort thread-safe?

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.

What is the function of To_string?

The to_string() method takes a single integer variable or other data type and converts into the string.


1 Answers

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.

like image 118
cpplearner Avatar answered Oct 06 '22 23:10

cpplearner