Simple C++ logger by using singleton pattern


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?

2/13/2012 6:02:42 PM

Accepted Answer

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

class 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

11/9/2009 2:44:45 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow