views:

75

answers:

2

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?

+1  A: 

The answer is probably lazy initialization. There's a lot of data behind the locale system, and it's pretty easy to make the mistake of coding the sequence:

  1. take lock
  2. check for initialization
  3. read data if needed
  4. release lock

and there you are.

Some of us don't trust the entire iostream mechanism as far as we can throw it from a threading performance standpoint. Since, oh, 1987, it has been full of unwanted locks with no way to declare that a single stream will be only used in a single thread.

bmargulies
+2  A: 

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.

Charles Bailey