Sponsored Content
Full Discussion: C++ singleton
Top Forums Programming C++ singleton Post 302710949 by achenle on Friday 5th of October 2012 06:17:26 AM
Old 10-05-2012
Quote:
Originally Posted by JohnGraham
No - make a private static variable that is a pointer to your object type. Make sure it's NULL initially. Then at each request, check if this pointer is NULL - if it is, then no instance of your object has been initialized, so construct one and return it. If it is non-NULL, just return it:

Code:
class Single
{
private:
    static Single *single;  // Initialize to NULL at definition.
    Single();
public:
    static Single *getSingle() {
        if (!single)
            single = new Single();  // Only gets called once, then if() statemenet is false.
        return single;
    }
};

Not quite. That's just hoping your constructor only gets called once.

Code:
class Single
{
private:
    static Single *single;  // Initialize to NULL at definition.
    Single();
public:
    static Single *getSingle()
    {
        // if we've already created the singleton, no need to spend the time
        // needed to lock and unlock the mutex
        if ( !single )
        {
            static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

            pthread_mutex_lock( &mutex );

            // need to check again in case another thread created the singleton
            // while this thread was blocked waiting for the mutex
            if ( !single )
            {
                single = new Single();  // Only gets called once, then if() statemenet is false.
            }

            pthread_mutex_unlock( &mutex );
        }
        return single;
    }
};

 

3 More Discussions You Might Find Interesting

1. Programming

What is singleton class ?

hello members, What is singleton class in c++ and in which case we will go with singleton class. Thanks & Regards Rajkumar_g (2 Replies)
Discussion started by: rajkumar_g
2 Replies

2. Programming

C++ abstract (singleton) factory implementation...

I want to create an abstract factory template which will allow me to pass in an "ID" for a subclass and return the singleton instance of that class stored in the factory. It'd be easy to adapt for "multi-ton", but for its present use this isn't necessary. The requirements are: - I don't want... (2 Replies)
Discussion started by: DreamWarrior
2 Replies

3. UNIX for Beginners Questions & Answers

AIX errpt : ( E7A89C7D Local adapter disabled after unstable singleton for long time )

Medel : 9117-MMC OS: AIX 6.1 Patch level : 6100-07-04-1216 Hacmp version : HACMP v 6.1.0.8 Oracle : 11.2.0.3 RAC Node : 2 node Dear, my one node server has been restarted early this morning, So, i tried to start HA and Oracle database. after that, the follow error appears at the node... (1 Reply)
Discussion started by: tomato00
1 Replies
All times are GMT -4. The time now is 06:00 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy