0

I have read this article (https://blogs.msdn.microsoft.com/oldnewthing/20040308-00/?p=40363), so i have written such code to protect the initialization of a local static object to be thread-safe.

I fear of making mistakes (some logic errors) or performance issues, so could you review my code or give me some hints to make it better, please.

My code (Platform is Windows):

static MyClass& get(void)
{
    enum { uninitialized = 0, initializing, initialized };
    static long state; // this will initialize to zero becuase it's static

// lock and intitialize or wait until intitialized
for(bool condition = false; !condition;)
{
    switch(compareExchange32(&state, initializing, uninitialized))
    {
    case uninitialized:     // object has to be created
    case initialized:    // object is already created
        condition = true;
        break;
    default:    // we wait for creation
        break;
    }
}

// Thread-safe initialization of object ?
static MyClass _instance;

// release lock
exchange32(&state, initialized);

return _instance;

}

Christian
  • 73
  • 6
  • 2
    http://codereview.stackexchange.com/ -- better place to ask that – Yam Marcovic Feb 16 '16 at 13:09
  • @YamMarcovic It's necessary to note that SE Codereview requires a **fully working** code posted in the question. – πάντα ῥεῖ Feb 16 '16 at 13:20
  • _@Christian_ For threadsafe static initialization you should refer to [Scott Meyer's singleton](http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289) implementation. – πάντα ῥεῖ Feb 16 '16 at 13:23
  • @πάνταῥεῖ I have no C++11 compiler, so the local static initialization is not guaranteed to be thread-safe! – Christian Feb 16 '16 at 13:37
  • I'm voting to close this question as off-topic because it is about code review and belongs on codereview.stackexchange.com – Daij-Djan Feb 16 '16 at 13:38

1 Answers1

0

Note that the C++ standard now supports thread-safe init of statics, no need for hand-hacking. See e.g. link to description of compiler impl of thread-safe static singleton

and

SO answer with link to standard

I now see that you have updated your question and that you do not have a C++11 compiler. But can you not use e.g. pthreads or similar to avoid hand -hacking synchronization? If performance is critical, maybe you have to use atomic ops.

Community
  • 1
  • 1
Erik Alapää
  • 2,335
  • 10
  • 23