Reputation: 1491
I know that a Scott Meyers Singleton is thread-safe for C++11 and above. Is the following code also thread-safe (for C++11 and above)?
class T
{
static T* obj;
public:
T& GetInstance()
{
if (!obj)
{
obj = new T();
}
return *obj;
}
};
T* T::obj=nullptr;
Upvotes: 2
Views: 97
Reputation: 14815
It is not thread-safe:
Two threads calling GetInstance
at the same time could both enter the if
block and allocate twice.
The returned object could also mismatch.
Upvotes: 3
Reputation: 180415
No, this code is not thread safe. Two or more different threads could all call GetInstance
at the same time and since obj
has no synchronization (mutex, atomic variable) guarding it, then you have a data race. Having a data race means your code has undefined behavior which is not safe.
Upvotes: 5