简单的C ++记录器通过使用单例模式 [英] Simple C++ logger by using singleton pattern

查看:112
本文介绍了简单的C ++记录器通过使用单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于使用Singleton模式实现记录器的泛滥示例,我刚刚为我的程序编写了一个简单的C ++记录器。然而,由于着名的双重锁定方法已知不再是线程安全的,我想知道是否应该:



1)忘记使用Singleton模式在这种情况下?



2)即使不安全,继续使用双重检查锁定?



3 )使用昂贵的纯同步锁定方法来访问其公共接口?



任何建议?

解决方案

使用Meyers Singleton。如果你使用gcc,至少初始化是线程安全的。

  class Singleton {
Singleton(){
//这是gcc中的线程安全,不需要互斥锁
}
static Singleton * instance(){
static Singleton myinstance;
return& myinstance;
}
};

gcc保护静态本地建筑,除非您使用-fno-threadsafe-statics禁用,我最近写了 here


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?

解决方案

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

这篇关于简单的C ++记录器通过使用单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆