当前位置:网站首页>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()
}
}
边栏推荐
- 图形视图框架
- Oracle-游标
- 杰理之样机无触摸,拆机之后重新安装变正常【篇】
- [autosar-dcm] - 4.3-how UDS $22 and $2e services read and write NVM data
- Market Research - current situation and future development trend of preclinical medical device testing service market
- Solve the error of changing the selected file when uploading excel file. Net:: err_ UPLOAD_ FILE_ CHANGED
- Market Research - current market situation and future development trend of intravenous injection (IV) bottles
- 高并发介绍及应对
- 对象与对象变量
- Market Research - current market situation and future development trend of genome editing mutation detection kit
猜你喜欢
电商系统微服务架构
Objects and object variables
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
Mathematical modeling -- graph and network models and methods (I)
Struct, bit segment, enumeration, union
[foreign journal] sleep and weight loss
建立自己的网站(22)
540. Single element in ordered array
Oracle cursor
随机推荐
Storage unit conversion
uniapp微信登录返显用户名和头像
[foreign journal] sleep and weight loss
Phpcms realizes the direct Alipay payment function of orders
杰理之修改不需要长按开机功能【篇】
世界环境日 | 周大福用心服务推动减碳环保
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
Baidu AI Cloud - create a face recognition application
wait解决僵尸进程
牛客网:最大子矩阵
Market Research - current situation and future development trend of anti-counterfeiting label market
LxC terminal login method
Market Research - current market situation and future development trend of aircraft audio control panel system
How should programmers write logs
Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
Zhong Xuegao responded that the product will not melt for 1 hour: it contains solid components and cannot melt into water
解决 excel 文件上传时更改选中的文件出现错误net::ERR_UPLOAD_FILE_CHANGED
UE4 game architecture learning notes
杰理之如何测试按键的误触率【篇】
Market Research - current market situation and future development trend of night vision goggles for pilots