0

I am creating a singleton class in the multithreaded environment and any thread can delete the singleton object. I want to protect this. I read somewhere to avoid this problem we can make the destructor private and can provide a destroy method.. how can we do this? Sample code will help..

Thanks in advance.

hiteshg
  • 81
  • 1
  • 5
  • Don't use a singleton. Make an abstract class and pass around an instance of a subclass. – Peter Wood Apr 17 '12 at 07:00
  • Simple solution don't give them a pointer. Give the user a reference then they are not allowed to delete it. See: http://stackoverflow.com/a/1008289/14065 – Martin York Apr 17 '12 at 08:35

3 Answers3

4
class Singleton; // forward declaration

Singleton * s = NULL; // global object available to all threads

// Place this class in a location unavailable to all threads except Main thread
class ManageSingleton
{
    public:
        static void DestroySingleton(Singleton * s)
        {
            delete s;
        }
}

class Singleton
{
    friend class ManageSingleton;
    protected:
        ~Singleton() {}
};

void main()
{
    s = new Singleton;
    while (...)
    {
       // other threads access Singleton object until program is finished 
    }

    // Program is now finished; destroy Singleton object
    ManageSingleton::DestroySingleton(s);
}
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
Dan Nissenbaum
  • 13,558
  • 21
  • 105
  • 181
3

threading really works against this design, especially if you want a pure singleton. you can visualize it like so:

class t_singleton {
public:
  static t_singleton& Get() {
    /* thread safety is a consideration here: */
    t_auto_ptr<t_singleton>& shared(Shared());
    if (shared.isNull()) {
      shared.setObject(new t_singleton);
    }
    /* and you should manage external references using another container type: */
    return Shared().reference();
  }
  static void DestroyIt() {
    /* thread safety is a consideration here: */
    Shared().destroy();
  }
private:
  static t_auto_ptr<t_singleton>& Shared() {
    static t_auto_ptr<t_singleton> s_Shared;
    return s_Shared;
  }
private:
  t_singleton();
  ~t_singleton();
};

but this should also suggest many threading red flags with pure singletons.

If you really want to extend this and enforce a pure singleton, you would need proper reference counting containers -- this suggests a singleton is a bad solution for this problem in multiple ways, and just adds a ton of unnecessary complexity. good luck!

justin
  • 104,054
  • 14
  • 179
  • 226
1

Make the destructor private and provide a Destroyer class that is responsible for destroying and cleaning up all the memory of the Singleton. It will need to be a friend of the Singleton class. To add to that, are you sure you absolutely need a singleton? Or is this another overuse scenario?

keelerjr12
  • 1,693
  • 2
  • 19
  • 35