Sujet : Re: Pre-main construction order in modules
De : eesnimi (at) *nospam* osa.pri.ee (Paavo Helde)
Groupes : comp.lang.c++Date : 31. Mar 2025, 13:26:30
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vse1lm$8iai$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11
User-Agent : Mozilla Thunderbird
On 31.03.2025 12:11, Bonita Montero wrote:
Am 31.03.2025 um 10:56 schrieb Paavo Helde:
Before C++11 one had to just add their own synchronization for thread safety (assuming multi-threaded access was needed, which was not so often in the past).
C++11 just made coding of a Meyer's singleton easier, that's all.
That's not that easy since it is undefined when a static local variable
is initialized before C++11. You'd have to wrap it in a union and leave
only member which is the object uninitialized. That's possible, but
that's not Meyer's singleton.
Thread synchronization has been possible since the introduction of threads. Otherwise they would not have been usable.
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;
}