473,666 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this Singleton class thread-safe?

Hello

I have written a singleton class like this:

//---------------------------------------------------------------------------
// Instance
//---------------------------------------------------------------------------
template <typename T>
T * CSingleton<T>:: Instance(
) throw()
{
static T inst;
return &inst;
}

Is this thread safe? Could two threads (with cpu context switching)
possibly create more than one instance of the class passed as a
template? Is this possible? If it is I presume I must lock using
mutex or some mechanism before line - static T inst; and just after
it?

Angus

Nov 14 '07 #1
4 3196
DJ
Angus napisał(a):
Hello

I have written a singleton class like this:

//---------------------------------------------------------------------------
// Instance
//---------------------------------------------------------------------------
template <typename T>
T * CSingleton<T>:: Instance(
) throw()
{
static T inst;
return &inst;
}

Is this thread safe? Could two threads (with cpu context switching)
possibly create more than one instance of the class passed as a
template? Is this possible? If it is I presume I must lock using
mutex or some mechanism before line - static T inst; and just after
it?
It is not thread safe and you must lock it, however mutex lock might
give performace penalty - depends on yours app. There is something
called double-checking locking - google for that - it's well known and
described problem
Nov 14 '07 #2
DJ wrote:
Angus napisał(a):
>Hello

I have written a singleton class like this:

//---------------------------------------------------------------------------

// Instance
//---------------------------------------------------------------------------

template <typename T>
T * CSingleton<T>:: Instance(
) throw()
{
static T inst;
return &inst;
}

Is this thread safe? Could two threads (with cpu context switching)
possibly create more than one instance of the class passed as a
template? Is this possible? If it is I presume I must lock using
mutex or some mechanism before line - static T inst; and just after
it?

It is not thread safe and you must lock it, however mutex lock might
give performace penalty - depends on yours app. There is something
called double-checking locking - google for that - it's well known and
described problem

Some compilers do make sure it's thread safe (see G++ past V4).

DCL (double checked locking) is not considered a good thing because it
does not work on all machines - see past articles on
comp.programing .threads.
Nov 14 '07 #3
DJ
Gianni Mariani napisał(a):
DJ wrote:
>Angus napisał(a):
>>Hello

I have written a singleton class like this:

//---------------------------------------------------------------------------

// Instance
//---------------------------------------------------------------------------

template <typename T>
T * CSingleton<T>:: Instance(
) throw()
{
static T inst;
return &inst;
}

Is this thread safe? Could two threads (with cpu context switching)
possibly create more than one instance of the class passed as a
template? Is this possible? If it is I presume I must lock using
mutex or some mechanism before line - static T inst; and just after
it?


It is not thread safe and you must lock it, however mutex lock might
give performace penalty - depends on yours app. There is something
called double-checking locking - google for that - it's well known and
described problem

Some compilers do make sure it's thread safe (see G++ past V4).
I am just thinking if you call ::Instace before threads are created in
the app you should be fine as the static object must be created,
shoudn't you ?
>
DCL (double checked locking) is not considered a good thing because it
does not work on all machines - see past articles on
comp.programing .threads.
true.
Nov 14 '07 #4
DJ wrote:
....
I am just thinking if you call ::Instace before threads are created in
the app you should be fine as the static object must be created,
shoudn't you ?
Yes.
>>
DCL (double checked locking) is not considered a good thing because it
does not work on all machines - see past articles on
comp.programin g.threads.

true.
Nov 14 '07 #5

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

Similar topics

10
2223
by: Opa | last post by:
I have tried for two days to solve this problem with no luck. I have a singleton class which has some events declared. When I inherit from this class the events don't seem to come along with it. The event in the singleton class always evaluates to null even when I cleary subscribe to it. Does anyone have some sample code of how to do this, or is this not possible.
7
2559
by: Robert W. | last post by:
I've just been reading all about the Singleton class and understand how to implement and use it but I cannot understand why one NEEDS to use it instead of just declaring a class and implementing Public Static variables therein. My usage revolves around global access to Reference Data. Some examples: - Countries, States-Provinces, Cities, Area Codes - Mobile Devices: Name, Description, Picture Filename and other sorts of data that will...
15
63901
by: DBA | last post by:
Hi All, What is the diff. between a singleton class and a static class in C#?
14
3019
by: Paul Bromley | last post by:
Forgive my ignorance on this one as I am trying to use a Singleton class. I need to use this to have one instance of my Class running and I think I understand how to do this. My question however is can a singleton class have a number of paramterised constructors enabling me to pass in parameters or not? I am trying to use the following to send in a parmeter to a constructor, but getting an error with it. I have a feeling that I am not...
2
1270
by: Michel van den Berg | last post by:
Hello, I tried to implement the GoF Singleton Pattern. What do you think? Public MustInherit Class Singleton(Of T As New) Public Sub New() If SingletonCreator.Creating = False Then Throw New SingletonException(Of T) End Sub
9
14140
by: Marcel Hug | last post by:
Hallo NG ! I Have a little question about inheritance of a singleton class. In my application i have a Database-Connection Lib, in which I would ¨like to connect different databases of the same project (thats why it is in a lib). For the database A I created a singleton class AProxy and for the database B the same as BProxy. Initializing and connetcing to the Database is the same in both classes (except of the database-path, which is a...
3
2960
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single
4
1462
by: Bryan | last post by:
Im new to threading and am experiencing some confusion as to how to correctly use AfxBeginThread in my singleton class. The code that I want to thread out is in a single function, Init(). Is AfxBeginThread the right way to thread off a single worker thread? It seems like it. But what are the correct args for it, my code wont compile. And does my class need to be restructured? How? Thanks, Bryan
3
3137
by: gzeng | last post by:
I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation? In the following is...
2
1881
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 SINGLETON_HPP template<typename T> struct DefaultCreatorFunctor {
0
8352
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7378
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4192
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2765
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.