473,230 Members | 1,580 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,230 software developers and data experts.

Is my Singleton template class OK

Hi,

I am wondering if My Singleton class is ok from a thread safety point
of view.

Am i adding the thread locks in the right places?
template <typename T>
class DLLEXPORT CSingleton
{
public:

// Return A reference to the instance of the CSingleton class.
// If there is no instance of the class yet, one will be created.
static T& Instance()
{
if (m_instance == 0 )
{
if (m_instance == 0)
{
#ifdef _WIN32
while (::InterlockedExchange(&m_lLocker, 1) != 0)
{
Sleep(1);
}
#endif
m_instance = new T;

// exit processing function
std::atexit(CSingleton::DestroyInstance);
#ifdef _WIN32
::InterlockedExchange(&m_lLocker, 0);
#endif
}
}
return *(CSingleton::m_instance);
};

// Destroys the CSingleton class instance.
// Be aware that all references to the single class instance will be
// invalid after this method has been executed!
static void DestroyInstance()
{
delete m_instance;
m_instance = NULL;
};

protected:

#ifdef _WIN32
static volatile long m_lLocker;
#endif

// shield the constructor and destructor to prevent outside sources
// from creating or destroying a CCSingleton instance.

inline explicit CSingleton() { CSingleton::m_instance =
static_cast<T*>(this); }
inline ~CSingleton() { CSingleton::m_instance = 0; }

private:

inline explicit CSingleton(CSingleton const&) {}
inline CSingleton& operator=(CSingleton const&) { return *this; }

private:

static T* m_instance; // CSingleton class instance
};

// static class member initialisation.
template <typename TT* CSingleton<T>::m_instance = 0;

#ifdef _WIN32
template <typename Tvolatile long CSingleton<T>::m_lLocker = 0;
#endif

Thanks if you got a chance to look at this.
Enda

Sep 29 '06 #1
2 2012
keepyourstupids...@yahoo.co.uk wrote:
I am wondering if My Singleton class is ok from a thread safety point
of view.

Am i adding the thread locks in the right places?
[snip]

You'll want to ask on comp.programming.threads or a group dedicated to
your platform since multithreading is off-topic here
(http://www.parashift.com/c++-faq-lit....html#faq-5.9). You
might also want to review chapter 6 of _Modern C++ Design_ by
Alexandrescu for more than you ever wanted to know about singletons in
C++ (including in a multithreaded environment). The updated code that
goes with the book can be found here:

http://sourceforge.net/projects/loki-lib/

Cheers! --M

Sep 29 '06 #2
On 29 Sep 2006 09:26:15 -0700, ke****************@yahoo.co.uk wrote:
>I am wondering if My Singleton class is ok from a thread safety point
of view.
Am i adding the thread locks in the right places?

template <typename T>
class DLLEXPORT CSingleton
{
public:

// Return A reference to the instance of the CSingleton class.
// If there is no instance of the class yet, one will be created.
static T& Instance()
{
if (m_instance == 0 )
{
if (m_instance == 0)
{
Your version of the double-checked locking pattern?
>#ifdef _WIN32
while (::InterlockedExchange(&m_lLocker, 1) != 0)
{
Sleep(1);
}
#endif
m_instance = new T;
When T's constructor throws an exception your Singleton is locked
forever. Familiarize youself with RAII. BTW, in general avoid
Singletons. They are just global variables disguised as design
pattern.

Best wishes,
Roland Pibinger

Sep 29 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Sean Dettrick | last post by:
Hi, apologies for yet another Singleton posting. From reading around previous postings etc, I've cobbled together two Singleton template definitions - one that returns a reference, and one that...
7
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a)...
1
by: Jim Strathmeyer | last post by:
So I'm trying to implement a singleton template class, but I'm getting a confusing 'undefined reference' when it tries to link. Here's the code and g++'s output. Any help? // singleton.h ...
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
5
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++...
2
by: yccheok | last post by:
hello, in a singleton design, i trying to make my parent class having protected constructor and destructor. however, the compiler give me error when my child, trying to delete itself through parent...
3
by: Raider | last post by:
I need to have one object for each template argument(s) used. For example, I need to have one object of int. I tried the following code and it gives me all I want with Visual C++ 7.1. But is it...
5
by: tobias.sturn | last post by:
Hi! I have written this template for making a singleton: #define DECLARE_SINGLETON(classname) \ private: \ static classname* m_pThis; \ classname(); \ class Guard \ { \ public: \
15
by: Nick Keighley | last post by:
Hi, I found this in code I was maintaining template <class SingletonClass> SingletonClass* Singleton<SingletonClass>::instance () { static SingletonClass _instance; return &_instance; }
2
by: Eric Lilja | last post by:
As the topic says, I wanted to make a re-usable singleton class that could create pointers to objects with non-trivial constructors. I came up with this: #ifndef SINGLETON_HPP #define...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.