Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
is it completely thread safe in C++ 98 if not, how we can achieve thread safe singleton in C++98 ?

MySingleton * GetInstance()
{
      if (m_pOnlyOneInstance == NULL)
      {
            EnterCriticalSection();
            if (m_pOnlyOneInstance == NULL)
            // Solution 1 and 2 gaps addressed by moving
            // critical section block and by re-doing this check!
            {
                  m_pOnlyOneInstance = new MySingleton();
            }
            LeaveCriticalSection();
      }
      return m_pOnlyOneInstance;
}


What I have tried:

In many of post it is written that it is not completely thread safe,in C++11 call_once() has solved the singleton thread_safe problem.How to do it in C++98?
Posted
Updated 14-Sep-17 1:46am
v2

1 solution

Hello,

Check the "C++ and the Perils of Double-Checked Locking"[^] article by Scott Meyers and Andrei Alexandrescu to find why the sample code you've got fails.

The article does provide a sample of thread-safe singleton. Yes, it does suffer from performance issue you are trying to solve with double checking. But it is thread safe. As for the performance, you need to have an idea of how often you are going to call the GetInstance() method before trying to find solution for it.
 
Share this answer
 
Comments
CPallini 14-Sep-17 7:59am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900