Sujet : Re: Pre-main construction order in modules
De : egenagwemdimtapsar (at) *nospam* jbohm.dk (Jakob Bohm)
Groupes : comp.lang.c++Date : 01. Apr 2025, 05:06:11
Autres entêtes
Organisation : Privat
Message-ID : <vsfonk$25iou$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13
User-Agent : Epyrus/2.1.3
On 2025-03-31 14:32, Bonita Montero wrote:
Am 31.03.2025 um 14:26 schrieb Paavo Helde:
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.
Artificial locking around ALL static locals as implemented by some
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.
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 of
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 .
Enjoy
Jakob
-- Jakob Bohm, MSc.Eng., I speak only for myself, not my companyThis public discussion message is non-binding and may contain errorsAll trademarks and other things belong to their owners, if any.