Re: Writing Singleton Classes

From: Tim Clacy (nospamtcl_at_nospamphaseone.nospamdk)
Date: 05/13/04


Date: Thu, 13 May 2004 21:08:40 +0200

cppaddict wrote:
> Hi,
>
> In this tutorial on singleton class in C++
> (http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the
> author gives two implementations of a simple singleton class, claiming
> that only the first is safe for multi-threaded appliactions. I want
> to know why this so.

cppaddict,

The first implementation needs a slight change to be thread-safe:

    Singleton* Singleton::Instance ()
    {
        // In the common case, simply return the existing instance (no
locking required)
        //
        if (pinstance != 0)
            return pinstance;

        // If there was no instance above, we need to lock now and
double-check whether
        // another thread created an instance in between the check above and
now
        //
        Lock();
        if (pinstance == 0)
            pinstance = new Singleton;
        Unlock();

        return pinstance;
    }

There are a dozen or so Singleton articles on CodeProject; the following is
very good and covers threading issues:

Singleton Pattern: A review and analysis of existing C++ implementations
http://www.codeproject.com/cpp/singleton.asp

Tim



Relevant Pages

  • Singleton Implementation Issue
    ... Unless I'm misunderstanding the pattern and it's various implementations, ... Singleton effectively makes the constructor unavailable to clients. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: question: static objects in LIB
    ... > lib file seems to override whatever singleton we implement. ... The function localtimeholds its own buffer of struct tm, ... From the Alexandrescu's book show some implementations of Singleton. ...
    (microsoft.public.vc.language)
  • Re: C++ singleton pattern question
    ... You don't control initialization in the first case. ... class Singleton ... const accessor also. ...
    (comp.lang.cpp)