13

We're using a

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

in a logger of ours that gets a UTF-16 string from a legacy component and converts it to UTF-8 that we write to the log. The converter gets instantiated on each conversion, upon which we do

auto utf8string = converter.to_bytes(utf16string);

This is done in a pretty intensive and multi-threaded part of our code and I'd like to re-use one instance of the converter, but seing that std::wstring_convert exposes a "state", I'm worried that to_bytes is not thread safe and any gains we could get by reusing the same instance would be lost by the excessive locking that would then be needed (in which case I wouldn't share the instance anyway).

So, is std::wstring_convert<>::to_bytes thread safe?

EDIT: A clarification on what I'm really asking: Given one instance of std::wstring_convert<>, if 2 or more threads concurrently call to_bytes on that instance with different arguments, is to_bytes then guaranteed to behave well?

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
  • @LucDanton: I think it's "allowed" to jot down a 2-line abstract of the important part ("const means thread safe") as an answer and add the link for the rest - then I can accept your answer. – Johann Gerell Sep 26 '14 at 07:41
  • A clarification to the above comment - the "const means thread safe" should be changed to "const means thread safe and to_bytes is not const, meaning it might change instance state" – Johann Gerell Sep 26 '14 at 07:49
  • @LucDanton: duh! thanks for noticing - changed it. Of course it's `to_bytes` (facepalm) – Johann Gerell Sep 26 '14 at 10:36

1 Answers1

5

Because std::wstring_convert is part of the Standard Library, it follows certain rules when it comes to handling an object of such type from different threads.

In particular, because both to_bytes and from_bytes overloads are non-const, it is not possible to use those members on any one particular object from different threads without synchronization. This makes sense, as codecvt conversions typically make use of a state_type object. Using it without synchronization would lead to disaster.

Community
  • 1
  • 1
Luc Danton
  • 34,649
  • 6
  • 70
  • 114