+ 1
Thread safe singleton | Need
Hi Please find below code for thread safe singleton design pattern. https://code.sololearn.com/coPeCoF9W7Wl Is it proper or not? Now another question is why we need thread safety? My getSingleton() method is responsible to create a object for class. As this is known, why should I call two threads even though I know that this method is suppose to create a single required object. Any thought on this or am I missing something?
1 Odpowiedź
+ 3
Since C++11 there is a rule in the standard that reads:
"If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization."
In other words, you do not need to lock your code and wait for the initialization to finish.
You can simply implement it as:
static Singleton& getSingleton()
{
static Singleton instance;
return instance;
}
Also, using new here as in your code will not call the destructor upon exiting the program whereas it will in this case.
Why do you need thread safety? Because getSingleton is called not just for initializing the object but also to get the object itself.
2 threads can call this function at the same time.
As for whether your code is thread safe, no it is not. You can read a better explanation as to why here:
https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf