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;
}