C++11 offers features like thread-safe initialization of static variables, and citing that question we'll say for instance:
Logger& g_logger() {
static Logger lg;
return lg;
}
So ostensibly (?) this is true regardless of whether a module compiled with a C++11 compiler included the thread headers, or spawned any threads in its body. You're offered the guarantee even if it were linked against another module that used C++11 threads and called the function.
But what if your "other module" that calls into this code wasn't using C++11 threads, but something like Qt's QThread
. Is atomic initialization of statics then outside of the scope of C++11's ability to make such a guarantee? Or does the mere fact of a module having been compiled with C++11 and then linked against other C++11 code imply that you will get the guarantee regardless?
Does anyone know a good reference where issues like this are covered?
Does anyone know a good reference where issues like this are covered?
Sure. The C++ standard. It describes the behavior of C++ code. If your library is C++ code, it is required to follow this behavior. So yes, you get the same guarantees as if it had been your own code.
Exactly how the compiler/runtime/OS/everything else pulls it off is Not Your Problem. The C++ standard guarantees that it is taken care of.
Your example relies on the memory model, not on how threads are implemented. Whoever executes this code will execute the same instructions. If two or more cores execute this code, they will obey the memory model.
The basic implementation is equivalent to this:
std::mutex mtx;
Logger * lg = 0;
Logger& g_logger() {
std::unique_lock<std::mutex> lck(mtx);
if (lg == 0)
lg = new Logger;
return *lg;
}
This code may be optimized to use the double-checked locking pattern (DCLP) which, on a particular processor architecture (e.g., on the x86) might be much faster. Also, because the compiler generates this code, it will know not to make crazy optimizations that break the naive DCLP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With