If multiple threads are invoking the function DoStuff
this will mean that the initialization code
if (mappedChars.empty())
can enter a race condition. This means thread 1 enters the function, finds the map empty and begins filling it. Thread 2 then enters the function and finds the map non-empty (but not completely initialized) so merrily begins reading it. Because both threads are now in contention, but one is modifying the map structure (i.e inserting nodes), undefined behaviour (a crash) will result.
If you use a synchronization primitive prior to checking the map for empty()
, and released after the map is guaranteed to have been completely initialized, all will be well.
I had a look via Google and indeed static initialization is not thread safe. Thus the declaration static mappedChars
is immediately an issue. As others have mentioned it would be best if your initialization was done when only 1 thread is guaranteed to be active for the life time of initialization.