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

发布于 2024-10-17 14:27:08 字数 332 浏览 1 评论 0原文

我听说并阅读了很多关于C++中的单例实现方法,例如Meyer、Phoenix等,但它们在某些使用场景中似乎都存在问题。因此,我想出了自己的实现方法,Daniel Singleton。我想知道的是它是否正确......我认为是的,但是请告诉我它是否有任何我没有想到的缺陷!

另外,我尝试通过使用双重检查锁定来使其线程安全,而无需始终获取锁,我也阅读了很多相关内容,每个人都说它已损坏。我也尝试解决这个问题,我想知道我的解决方案是否正确......如果不正确,那么它怎么会失败呢?

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. So I came up with my own implementation approach, the 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭ゆ眷念 2024-10-24 14:27:08

单例模式本身就被破坏了,因为它会产生可怕的代码。使用依赖注入/控制反转确实要好得多。请参阅我的关于避免单身的页面在这里

你的单例类不必要地复杂。看起来您正在实现惰性单例模式,并且仍然在获取锁,所以——除了让事情变得不必要的复杂之外——我不确定您所做的与更简单的惰性单例实现有何不同。您是否对您的实现进行了基准测试以确定它是否比更简单的替代方案更快?我希望看到明显的性能优势来应对更复杂的事情。

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.

眼眸里的那抹悲凉 2024-10-24 14:27:08

双重检查锁定模式类似于 ascii 和 IEE754 浮点。尽管没有正式保证,但可以相当安全地假设它在您见过的每个系统上都运行良好。

The double-checked locking pattern is like ascii and IEE754 floating points. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文