Elvis Dukaj
Elvis Dukaj

Reputation: 7368

C++ on singleton

I've a singleton class and I'm sure that the first call of the singleton is done by only one thread. I've implemented singleton with lazy initialization.

class MySingleton : private boost::noncopyable {
public:

    /** singleton access. */
    static MySingleton & instance()
    {
        static MySingleton myInstance;
        return myInstance;
    }

    void f1();
    void f2();
    void f3();
    void f4();

private:

    MySingleton();

};

Now I've another factory class that is responsable to create all singletons in a single thread enviorment. The singleton can be used from multiple threads and methods are protected from mutex.

First question

Is this approach accetable?

Second question

I've a complex class that must be thread safe.
This class has to be a singleton. How can that a calling of different methods of the class is thread safe. For example.

{ 
    MySingletonLock lock;
    // Other thread must wait here.
    MySingleton::instance().f1();
    MySingleton::instance().f3();
}

How can I get this?

Upvotes: 1

Views: 261

Answers (1)

Liviu
Liviu

Reputation: 1917

The answer to your second question:

class MyProtectedSingleton: public MySingleton
{
public:
   void f1()
   {
       MySingletonLock lock;
            // Other thread must wait here.
       MySingleton::instance().f1();    
   }

  void f2()
  {
      MySingletonLock lock;
        // Other thread must wait here.
      MySingleton::instance().f2();    
  }
};

Call f1, f2, etc through wrappers in MyProtectedSingleton.

Upvotes: 1

Related Questions