7

Due to the flooding examples of implementing logger using Singleton pattern, I have just written a simple C++ logger in the same approach for my program. However, since the famous double-checked locking approach is known to be no more thread-safe, I wonder if I should:

1) Forget about the use of Singleton pattern in this case?

2) Continue to use double-checked locking even though it is unsafe?

3) Use the expensive pure sync lock method for every access to its public interfaces?

Any suggestions?

1
  • 1
    Wow, I didn't expect responses come in so fast. I just realize that I made a stupid mistake. In my case there are basically two groups of interfaces that require safeguard: getInstance(), and the rest are for logger's client to initialize various log settings. My mistake was that, I have been spending lot of time to find an approach that will safeguards both type of interfaces, hopefully with balanced efficiency. Why must I use one, and ONLY one approach? I can use either the suggestion from Arkaitz or stefaanv for getInstance(); then use the basic sync lock for settings initialization.
    – shiouming
    Nov 9, 2009 at 15:16

4 Answers 4

16

Use Meyers Singleton. If you are using using gcc at least initialization is thread-safe.

class Singleton{
   Singleton(){
    //This is threadsafe in gcc, no mutex required
   }
   static Singleton * instance(){
      static Singleton myinstance;
      return &myinstance;
   }
};

gcc guards static locals construction unless you disable with -fno-threadsafe-statics, I recently wrote about that here

10
  • Wouldn't you want instance() to be static?
    – Aaron
    Nov 9, 2009 at 14:18
  • 2
    It should be return &myinstance;.
    – irh
    Nov 9, 2009 at 14:43
  • 13
    Instead of returning Singleton *, return Singleton &. It prevents someone from accidentally doing the following: Singleton *instance = Singleton::instance(); ...lines of code... delete instance;
    – moswald
    Nov 9, 2009 at 15:43
  • 3
    Please dont return a pointer. If you do that you open up a whole can of worms regarding who owns the pointer (and thus who should release it). By returning a reference you are indicating your code retains ownership and thus will handle the destruction. (Note in modern C++ code you should hardly ever be returning a RAW pointer). Nov 9, 2009 at 19:38
  • 2
    @PaulManta: Becuase they may think they can delete it. If you return a reference they now they can't delete. It is an indication of ownership. Which is why you practically never pass around pointers (there is no indication of ownership) in GOOD C++ code (unless you are still writing C with classes (Yes there is a lot of Bad C++ out there)). In C++ you pass around references or smart pointers as these are indications of ownership semantics. Feb 13, 2012 at 18:41
1

In applications with threads, I prefer to use singletons with an initialize() function and asserts to make sure that the initialize() is used before the first instance(). Call initialize() from the main thread. I don't think that lazy instantiation is really the key feature of a singleton, especially for a logger.

While Arkaitz's answer is more elegant, my answers avoids threading issues on all platforms with the cost of 1 extra function and some instantiating concerns during startup for singletons with dependencees (helped by asserts and ofcourse: use singletons judiciously).

5
  • I tend to like this answer, but with the caveat that you then can't use the logging during pre-initialization code. This isn't usually a big deal, but I've had it bite me once or twice. Nov 9, 2009 at 14:37
  • @Michael: when we decided for this approach, I actually suggested using your answer: accessing in the main thread. But this approach works for us and it makes sure that the singleton is always initialized in the main thread. If the access would be removed from the main thread, we would only find the first time there is a problem (in the field?)
    – stefaanv
    Nov 9, 2009 at 14:47
  • My existing code is pretty close to this approach. However, I also wondering if I should assume that logger's client code will always use/initialize the logger correctly, or should I perform any checking internally.
    – shiouming
    Nov 9, 2009 at 15:00
  • @shiouming: use asserts: in debug-mode you can't do anything else than first initialize(), especially since you have some user-settings. Do you have a dependency issue with first reading the user settings (without logger) and only then initializing the logger? Can this be solved with first using default settings?
    – stefaanv
    Nov 9, 2009 at 15:12
  • Yup, existing implementation uses default setting upon first call to getInstance(), either if client has not initialize the logger's setting, or it is not initialized correctly.
    – shiouming
    Nov 11, 2009 at 7:46
1

One approach would be to make sure that your first access to the logger comes before your app starts a second thread. By accessing the singleton at a time when you KNOW that there isn't any contention, you make sure that subsequent accesses will always find a pre-existing object and you should completely avoid the problem.

0

You do not really need separate Initialize() function as this will just contaminate your singleton interface. Just get singleton instance

VERIFY(NULL != Logger::Instance()); 

before any other thread has chance to access it.

2
  • You should not need to check a singelton for NULL. It exists or it does not exits. Returning a reference to singelton gurantess it exists. Nov 9, 2009 at 19:41
  • Thanks Mark. I agree that singleton getter must return reference, not pointer. My line refers to the snipped about Meyers singleton above that does return it by pointer. Although it appears that it can not fail, you never know who will be modifying your code down the road. So VERIFY here is just a time capsule for future programmer. Nov 9, 2009 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.