Re: Writing Singleton Classes
From: Tim Clacy (nospamtcl_at_nospamphaseone.nospamdk)
Date: 05/13/04
- Next message: 1111111111: "Re: Please Help me on this Program"
- Previous message: cppaddict: "Re: Writing Singleton Classes"
- In reply to: cppaddict: "Writing Singleton Classes"
- Next in thread: DaKoadMunky: "Re: Writing Singleton Classes"
- Reply: DaKoadMunky: "Re: Writing Singleton Classes"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: 1111111111: "Re: Please Help me on this Program"
- Previous message: cppaddict: "Re: Writing Singleton Classes"
- In reply to: cppaddict: "Writing Singleton Classes"
- Next in thread: DaKoadMunky: "Re: Writing Singleton Classes"
- Reply: DaKoadMunky: "Re: Writing Singleton Classes"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|