Liste des Groupes | Revenir à cl c++ |
On 2025-03-31 14:32, Bonita Montero wrote:The synchronization of static variable initialization (which may or may not involve locking) is demanded by the C++11 standard (so it is pretty portable) and makes it easier, faster, safer, and more maintainable to use statics in multithreaded C++ code (which is "most code" in my area).Am 31.03.2025 um 14:26 schrieb Paavo Helde:Artificial locking around ALL static locals as implemented by some
>An example of pre-C++11 thread-safe Meyer singleton:>
>
std::map<std::string, std::string>& GetGlobalMap() {
>
// No dynamic initialization, so this is safe:
static std::map<std::string, std::string>* pGlobal = NULL;
>
// No dynamic initialization, so this is safe as well:
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
>
// Initialize the global static if not yet initialized.
pthread_mutex_lock(&mutex);
if (!pGlobal) {
pGlobal = new std::map<std::string, std::string>();
}
pthread_mutex_unlock(&mutex);
return *pGlobal;
}
That's rather slow. Double-checked locking as implemented for
all static locals with current runtimes is much more efficient.
modern compilers is highly wasteful as in most code, the code
structure already ensures a single thread will be the first to
execute that initialization/construction,
often one of the threads in the compiler itself.Sorry, cannot parse that sentence.
That locking by compilers seem to be the result of someone in the C++ ctte wanting to take over every OS feature that used to be out ofHow comes? In some lower level code you one might just not use dynamic initialization of statics, which avoids any need of thread synchronization.
scope for system programming languages like C/C++.
It also makes it
unnecessarily harder to use the system compiler to implement the lower
level code that exists at a more fundamental / portable level than
silly textbook examples .
Les messages affichés proviennent d'usenet.