Thread safe singleton | Need | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
+ 1

Thread safe singleton | Need

Hi Please find below code for thread safe singleton design pattern. 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 Resposta
+ 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:
5th May 2021, 2:44 PM
Dennis - avatar