Thread safe singleton | Need | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

5th May 2021, 1:36 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 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
5th May 2021, 2:44 PM
Dennis
Dennis - avatar