This question made me question a practice I had been following for years.
For thread-safe initialization of function-local static const objects I protect the actual construction of the object, but not the initialization of the function-local reference referring to it. Something like this:
namespace {
const some_type& create_const_thingy()
{
lock my_lock(some_mutex);
static const some_type the_const_thingy;
return the_const_thingy;
}
}
void use_const_thingy()
{
static const some_type& the_const_thingy = create_const_thingy();
// use the_const_thingy
}
The idea is that locking takes time, and if the reference is overwritten by several threads, it won’t matter.
I’d be interested if this is
- safe enough in practice?
- safe according to The Rules? (I know, the current standard doesn’t even know what “concurrency” is, but what about trampling over an already initialized reference? And do other standards, like POSIX, have something to say that’s relevant to this?)
The reason I want to know this is that I want to know whether I can leave the code as it is or whether I need to go back and fix this.
For the inquiring minds:
Many such function-local static const objects I used are maps which are initialized from const arrays upon first use and used for lookup. For example, I have a few XML parsers where tag name strings are mapped to enum values, so I could later switch over the tags’ enum values.
Since I got some answers as to what to do instead, but haven’t got an answer to my actual questions (see 1. and 2. above), I’ll start a bounty on this. Again:
I am not interested in what I could do instead, I do really want to know about this.
This is my second attempt at an answer. I’ll only answer the first of your questions:
No. As you’re stating yourself you’re only ensuring that the object creation is protected, not the initialization of the reference to the object.
In absence of a C++98 memory model and no explicit statements from the compiler vendor, there are no guarantees that writing to the memory representing the actual reference and the writing to the memory that holds the value of the initialization flag (if that is how it is implemented) for the reference are seen in the same order from multiple threads.
As you also say, overwriting the reference several times with the same value should make no semantic difference (even in the presence of word tearing, which is generally unlikely and perhaps even impossible on your processor architecture) but there’s one case where it matters: When more than one thread races to call the function for the first time during program execution. In this case it is possible for one or more of these threads to see the initialization flag being set before the actual reference is initialized.
You have a latent bug in your program and you need to fix it. As for optimizations I’m sure there are many besides using the double-checked locking pattern.