15

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?

10
  • 8
    Nothing about that quotes says it is not thread safe. It is just that multiple calls might not run concurrently. That is a performance issue, not a safety one. Commented Jul 18, 2017 at 19:44
  • 1
    @Nathan Begs the question is std::locale thread safe? Commented Jul 18, 2017 at 19:51
  • 1
    @NeilButterworth Parts of it are not. For instance setlocale is not thread safe so std::to_string might use a mutex to make sure multiple calls don't race if it calls that. Commented Jul 18, 2017 at 19:56
  • 1
    @NathanOliver That seems pretty insanely hideous and non-performant if std::to_string involved locking a mutex. Commented Jul 18, 2017 at 19:58
  • 1
    As to class std::locale itself: it is immutable, so there is no possibility of read/write race Commented Jul 18, 2017 at 19:58

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.