简体   繁体   English

C ++单例实现,双重检查锁定

[英]C++ singleton implementation, double-checked locking

I heard and read a lot about singleton implementation approaches in C++, like Meyer, Phoenix, etc., but all of them seemed to have a problem in certain usage scenarios. 我听到并阅读了很多有关C ++中的单例实现方法的信息,例如Meyer,Phoenix等,但是在某些使用情况下,它们似乎都存在问题。 So I came up with my own implementation approach, the Daniel Singleton . 因此,我想出了自己的实现方法Daniel Singleton What I would like to know is if it's correct or not... I think it is, but please tell me if it has any flaws I did not think of! 我想知道的是,是否正确……我认为是正确的,但是请告诉我它是否有我没有想到的缺陷!

Also, I tried to make it thread-safe without acquiring locks all the time by using double-checked locking, which I read a lot about too, and everybody stated that it's broken. 另外,我尝试通过使用双重检查锁定来使它始终保持线程安全,而不必一直获取锁定,对此我也有很多了解,每个人都说它已损坏。 I tried to fix that too, and I'd like to know if my solution is correct or not... and if it's not, then how can it fail? 我也尝试修复此问题,我想知道我的解决方案是否正确...如果不正确,那么它怎么会失败?

The singleton pattern, itself, is broken in that it makes for horrible code. 单例模式本身就被破坏了,因为它造成了可怕的代码。 It's really much better to use dependency injection / inversion of control. 使用依赖注入/控制反转确实好得多。 See my page on avoiding singletons here . 请参阅我关于避免单例的页面

Your singleton class is needlessly complicated. 您的单例课程不必要地复杂。 It looks like you are implementing the lazy singleton pattern, and you are still acquiring a lock, so -- aside from making things needlessly convoluted -- I'm not sure how what you are doing is much different from simpler lazy singleton implementations. 看起来您正在实现惰性单例模式,并且仍在获取锁,因此-除了使事情不必要地复杂化之外-我不确定您的操作与更简单的惰性单例实现有何不同。 Have you benchmarked your implementation to determine if it is any faster than the simpler alternatives? 您是否已对实现进行基准测试,以确定它是否比简单的替代方案更快? I would want to see a clear performance win to go with something that is way more complicated. 我希望看到更复杂的东西能获得明显的性能胜利。

The double-checked locking pattern is like ascii and IEE754 floating points. 双重检查的锁定模式类似于ascii和IEE754浮点。 It's fairly safe to assume that it works well enough on every system you'll ever see, even though it's not formally guaranteed. 可以肯定地说,即使没有正式的保证,它也可以在您将看到的每个系统上运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM