使用单例模式的简单C ++记录器 [英] Simple C++ logger by using singleton pattern
问题描述
由于使用Singleton模式实现记录器的洪水示例,我刚刚在我的程序中使用相同的方法编写了一个简单的C ++记录器。但是,由于着名的双检查锁定方法已知不再线程安全,我不知道我应该:
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)忘记使用Singleton模式在这种情况下?
1) Forget about the use of Singleton pattern in this case?
2)继续使用双重锁定,即使它不安全吗?
2) Continue to use double-checked locking even though it is unsafe?
3 )
有任何建议吗?
推荐答案
使用Meyers Singleton。如果你使用gcc,至少初始化是线程安全的。
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保护静态局部构造,除非你使用-fno-threadsafe-statics禁用, 此处
gcc guards static locals construction unless you disable with -fno-threadsafe-statics, I recently wrote about that here
这篇关于使用单例模式的简单C ++记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!