Implementaion of ThreadSafe Singleton class in C++?

Discussion in 'Programming' started by sumyaonnet, Oct 8, 2009.

  1. #1
    Can any one suggest how can we implement threadsafe singleton class, What are the createria' that needs to be satified ?

    What if we inherit from such class, derived just get the singleton nature ?
     
    sumyaonnet, Oct 8, 2009 IP
  2. brian65

    brian65 Active Member

    Messages:
    1,172
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    88
    #2
    The question is not entirely clear but if your intention is to protect access to a resource, e.g. a member variable, by mutliple threads, you could look at using the C++ Mutex class.
     
    brian65, Oct 8, 2009 IP
  3. bizhobby

    bizhobby Peon

    Messages:
    692
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    class Singleton {
        Singleton();
        ~Singleton();
        static Singleton *s_singleton;
        static void init();
      public:
        static Singleton& instance();
    };
    Singleton *Singleton::s_singleton = 0;
    void Singleton::init() {
        static Singleton singleton;
        s_singleton = &singleton;
    }
    Singleton& Singleton::instance() {
        lock(&mutex);
        if (!s_singleton) {
            init();
        }
        unlock(&mutex);
        return *s_singleton;
    }
    
    Code (markup):
    (From Dr. Dobb's article, but could not post the link)

    I would also highly recommend taking a look at the boost library for a platform independent solution.

    You don't want to write something Windows specific and then have to port it to Linux/Mac, etc.
    (or vice versa)

    Hope that helps.
     
    bizhobby, Oct 9, 2009 IP