Search code examples
c++localizationinternationalizationlocalemutex

Explain the Need for Mutexes in Locales, Please


Reading the question Why doesn’t C++ STL support atoi(const string& ) like functions?, I encountered a comment which warned that GCC (at least) has a bug that can slow down multi-threaded applications which use ostringstream frequently. This is apparently due to a mutex 'needed' by the C++ locale machinery.

Given my recent interest in globalization practices, I wonder if anyone can explain to me why a locale object would need a mutex? What is it that can be changed in a locale that needs a mutex? Shouldn't it be a read-only facility?


Solution

  • It's really an implementation issue, but std::locale has a static function that retrieves and set the 'global' locale. The global locale is defined to be used in several areas of the standard library which implies that there must be a global locale somewhere.

    In implementations that support threads it is very likely that this global locale needs to be protected via some sort of locking mechanism to prevent simultaneous access between threads from causing undesired behaviour.

    As the current standard does not explicitly deal with threading at all, it's a set implementation choices as to how (or if) this locking mechanism is implemented and whether other shared data and locks are required.