当前位置:网站首页>go 4種單例模式
go 4種單例模式
2022-07-02 22:49:00 【給我一瓶冰闊洛】
懶漢式——非線程安全
非線程安全,指的是在多線程下可能會創建多次對象。
//使用結構體代替類
type Tool struct {
values int
}
//建立私有變量
var instance *Tool
//獲取單例對象的方法,引用傳遞返回
func GetInstance() *Tool {
if instance == nil {
instance = new(Tool)
}
return instance
}
在非線程安全的基本上,利用 Sync.Mutex 進行加鎖保證線程安全,但由於每次調用該方法都進行了加鎖操作,在性能上不是很高效
//鎖對象
var lock sync.Mutex
//加鎖保證線程安全
func GetInstance() *Tool {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = new(Tool)
}
return instance
}
餓漢式
直接創建好對象,不需要判斷為空,同時也是線程安全,唯一的缺點是在導入包的同時會創建該對象,並持續占有在內存中。
Go語言餓漢式可以使用 init 函數,也可以使用全局變量。
type cfg struct {
}
var cfg *config
func init() {
cfg = new(config)
}
// NewConfig 提供獲取實例的方法
func NewConfig() *config {
return cfg
}
type config struct {
}
//全局變量
var cfg *config = new(config)
// NewConfig 提供獲取實例的方法
func NewConfig() *config {
return cfg
}
雙重檢查
在懶漢式(線程安全)的基礎上再進行優化,减少加鎖的操作,保證線程安全的同時不影響性能。
//鎖對象
var lock sync.Mutex
//第一次判斷不加鎖,第二次加鎖保證線程安全,一旦對象建立後,獲取對象就不用加鎖了。
func GetInstance() *Tool {
if instance == nil {
lock.Lock()
if instance == nil {
instance = new(Tool)
}
lock.Unlock()
}
return instance
}
sync.Once
通過 sync.Once 來確保創建對象的方法只執行一次
var once sync.Once
func GetInstance() *Tool {
once.Do(func() {
instance = new(Tool)
})
return instance
}
sync.Once 內部本質上也是雙重檢查的方式,但在寫法上會比自己寫雙重檢查更簡潔,以下是 Once 的源碼
func (o *Once) Do(f func()) {
//判斷是否執行過該方法,如果執行過則不執行
if atomic.LoadUint32(&o.done) == 1 {
return
}
// Slow-path.
o.m.Lock()
defer o.m.Unlock()
//進行加鎖,再做一次判斷,如果沒有執行,則進行標志已經掃行並調用該方法
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
边栏推荐
- [LeetCode] 存在重复元素【217】
- 手写ORM(对象关系映射)增删改查
- 杰理之修改不需要长按开机功能【篇】
- Oracle-游标
- Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
- Hanoi Tower problem
- Market Research - current situation and future development trend of sickle cell therapy Market
- Struct, bit segment, enumeration, union
- Perceptron model and Application
- Market Research - current market situation and future development trend of aircraft front wheel steering system
猜你喜欢
随机推荐
图形视图框架
Introduction to database system Chapter 1 short answer questions - how was the final exam?
建立自己的网站(22)
Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens
Using rendertext() to output multiple lines of text with rendertext() in R shiny
Oracle-PL/SQL编程
杰理之直接触摸样机的顶针反应不正常【篇】
高并发介绍及应对
It's not easy to say I love you | use the minimum web API to upload files (swagger support) # yyds dry inventory #
Unity publishes a method of webgl playing sound
数学建模——图与网络模型及方法(一)
UE4 游戏架构 学习笔记
杰理之样机无触摸,拆机之后重新安装变正常【篇】
分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
Storage unit conversion
用sentinel熔断比例阈值改不了,设置慢调用比例没效果
Market Research - current situation and future development trend of anti-counterfeiting label market
E-commerce system microservice architecture
Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
[LeetCode] 回文数【9】