Simple C++ logger by using singleton pattern

前端 未结 4 1923
旧巷少年郎
旧巷少年郎 2021-02-09 17:28

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 famo

相关标签:
4条回答
  • 2021-02-09 17:35

    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 讨论(0)
  • 2021-02-09 17:47

    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).

    0 讨论(0)
  • 2021-02-09 17:56

    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

    0 讨论(0)
  • 2021-02-09 17:58

    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.

    0 讨论(0)
提交回复
热议问题