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?
Based on this, when I'm setting the function the std::function object points to, for this use case the std::function object is not thread safe.
A function is already thread safe if it doesn't modify non-local memory and it doesn't call any function that does. In this (trivial) case, you don't have to do anything. You really want to think about protecting data, not functions. For example, let's say that the function modifies non-local data structure X.
The standard doesn't guarantee anything about threads. So to do anything with threads in C++, you have to rely on implementation-defined guarantees. And Then you can safely use std::string because each implementation tells you whether or not it is safe to use in a threaded environment.
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.
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