0

In my C++ project I have a singleton class. During project execution, sometimes the same singleton class is accessed from two different thread simultaneously. Resulting in two instances of the singleton class is produced, which is a problem.

How to handle such a cases?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
  • 3
    Now you realized why not to use Singleton – Neel Basu Aug 20 '12 at 06:19
  • 1
    Use whatever tool you want that makes your life easier and doesn't complicate it too much. That includes singletons, anti-patterns, code smells, gotos, multiple exit points from a function, global variables and so on. Just understand the implications and potential issues, mitigating them if possible, throwing away the tool if not. I consider it near the height of arrogance to presume we know better whether a particular tool is suitable in a given case, without knowing the environment. End rant :-) – paxdiablo Aug 20 '12 at 06:39
  • Already answered here: http://stackoverflow.com/a/449823/14065 – Martin York Aug 20 '12 at 07:12
  • @Loki, not sure how you can tell it's the same issue as that supposed dupe. I don't think there's enough info in this question to be certain of that. – paxdiablo Aug 20 '12 at 09:01

4 Answers4

3

Then it's not a singleton :-)

You'll probably need to show us some code but your basic problem will be with the synchronisation areas.

If done right, there is no way that two threads can create two objects of the class. In fact, the class itself should be the place where the singleton nature is being enforced so that erroneous clients cannot corrupt the intent.

The basic structure will be:

lock mutex
if instance doesn't exist:
    instance = new object
unlock mutex

Without something like mutex protection (or critical code section or any other manner in which you can guarantee at the language/library level that two threads can't run the code simultaneously), there's a possibility that thread one may be swapped out between the check and the instantiation, leading to two possible instances of your "singleton".

And, as others will no doubt suggest, singletons may well be a bad idea. I'm not quite in the camp where every use is wrong, the usual problem is that people treat them as "god" objects. They can have their uses but there's often a better way, though I won't presume to tell you you need to change that, since I don't know your use case.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

If you get two different instances in different threads you are doing something wrong. Threads, unlike processes, share their memory. So memory allocated in one thread (e.g. for an object instance) is also usable in the other.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

If your singleton getting two copies its not guarded with mutex. lock a mutex when getting/accessing/setting the internal object.

I believe You are done something like this if(!_instance)_instance = new Singleton() there lies a critical section. which you need to safe guard with a mutex.

Neel Basu
  • 12,638
  • 12
  • 82
  • 146
1

Do not use a singleton, It is a well known Anti-Pattern.
A good read:
Singletons: Solving problems you didn’t know you never had since 1995

If you still want to persist and go ahead with it for reasons known only to you, What you need is a thread safe singleton implementation, something like this:

YourClass* YourClass::getInstance()
{
    MutexLocker locker(YourClass::m_mutex);
    if(!m_instanceFlag)
    {
        m_instance = new YourClass();
        m_instanceFlag = true;
    }
    return m_instance;
}

Where MutexLocker is a wrapper class for an normally used Mutex, which locks the mutex when creating its instance and unlocks the mutex the function ends.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I didn't downvote, Als, but I came close :-) It's usually the "god-object" aspect of singletons that causes problems rather than the singletons themselves. And provided you understand and manage the "global state" problem, singletons aren't so bad. The anti-pattern/code-smell/no-goto crowd need to be taught that all tools have their place. Yes, even goto. – paxdiablo Aug 20 '12 at 06:35
  • That and the fact that your anti-pattern link doesn't even deign to mention singletons :-) – paxdiablo Aug 20 '12 at 06:36
  • @paxdiablo: I disagree. *the "aren't so bad"* bad argument fails to impress me really. To summarize There is no need/use for a pattern like Singleton in a well designed software.I understand it is a long standing debatable issue, and any further debate can only flare war of words which I am not really keen on.So I will leave it at that. – Alok Save Aug 20 '12 at 06:41
  • @paxdiablo: The anti-pattern link is supposed to give a basic understanding/definition of what an Anti-Pattern is(*If one is unaware of the same*).We all know for a fact the perils of Singleton and that it is deemed as on of the Anti-Patterns. The linked excellent blog post by _@jalf already points out the same rather conclusively.I don't think there is any need to add anything over it to prove singleton as an Anti-Pattern. – Alok Save Aug 20 '12 at 06:45