简单的C ++记录器通过使用单例模式 [英] Simple C++ logger by using singleton pattern
问题描述
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屋!