Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient thread-safe singleton in C++

The usual pattern for a singleton class is something like

static Foo &getInst() {   static Foo *inst = NULL;   if(inst == NULL)     inst = new Foo(...);   return *inst;     } 

However, it's my understanding that this solution is not thread-safe, since 1) Foo's constructor might be called more than once (which may or may not matter) and 2) inst may not be fully constructed before it is returned to a different thread.

One solution is to wrap a mutex around the whole method, but then I'm paying for synchronization overhead long after I actually need it. An alternative is something like

static Foo &getInst() {   static Foo *inst = NULL;   if(inst == NULL)   {     pthread_mutex_lock(&mutex);     if(inst == NULL)       inst = new Foo(...);     pthread_mutex_unlock(&mutex);   }   return *inst;     } 

Is this the right way to do it, or are there any pitfalls I should be aware of? For instance, are there any static initialization order problems that might occur, i.e. is inst always guaranteed to be NULL the first time getInst is called?

like image 846
user168715 Avatar asked Apr 04 '10 21:04

user168715


People also ask

Can we make singleton as thread safe?

Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can't access it simultaneously.

Should you avoid singletons?

The truth is that singletons aren't inherently bad if they're used correctly. The goal of the singleton pattern is to ensure only one instance of a class is alive at any one time. That, however, is not the goal many developers have in mind when using singletons.

Are singletons thread safe C#?

How to Implement Singleton Pattern in C# code. There are several ways to implement a Singleton Pattern in C#. No Thread Safe Singleton.


1 Answers

If you are using C++11, here is a right way to do this:

Foo& getInst() {     static Foo inst(...);     return inst; } 

According to new standard there is no need to care about this problem any more. Object initialization will be made only by one thread, other threads will wait till it complete. Or you can use std::call_once. (more info here)

like image 79
Sat Avatar answered Sep 27 '22 17:09

Sat