Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are member functions of std::wstring_convert thread safe?

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?

like image 233
Johann Gerell Avatar asked May 20 '13 07:05

Johann Gerell


People also ask

Is std :: function thread safe?

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.

How do you make a function thread safe in C++?

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.

Is STD string thread safe?

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.


1 Answers

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.

like image 184
Luc Danton Avatar answered Sep 20 '22 17:09

Luc Danton