Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize double check for go singleton whether it is safe

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "go singleton how to achieve double detection is safe", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "go singleton how to achieve double detection is safe" bar!

Current situation

At present, some projects directly use Mutex locks, while others directly judge that nil is created. For the former, the performance of locking is poor every time, while for the latter, there will be multiple instances, so it is not a single instance.

Improve

If you want to improve it, instead of discussing hungry and thread-unsafe implementations here, there are two common lazy implementations of thread safety in go:

Double check sync.Once

Double check example: package main import ("sync"testing") var (instance * int lock sync.Mutexfunc getInstance () * int {if instance = = nil {lock.Lock () defer lock.Unlock () if instance = = nil {I: = 1 instance = & I}} return instance} / / for the following benchmark Try func BenchmarkSprintf (b * testing.B) {for iRanger 0 I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report