当前位置:网站首页>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()
}
}边栏推荐
- [shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
- php实现根据输入的年龄查询出生日期符合的数据
- Pointer array parameter passing, pointer parameter passing
- Niuke: Dragon and dungeon games
- Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
- Using rendertext() to output multiple lines of text with rendertext() in R shiny
- Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
- 杰理之如何测试按键的误触率【篇】
- Socket套接字C/S端流程
- 百度智能云-创建人脸识别应用
猜你喜欢

SimpleITK使用——3. 常见操作
![[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)](/img/4c/c8dae41fc2eb18b5153cf36861fc7d.jpg)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)

Jatpack------LiveData

Based on asp Net (used mobile phone sales management system) +asp Net+c # language +vs2010+ database can be used for course design and post design learning

NC50965 Largest Rectangle in a Histogram

Pointer and string
![[LeetCode] 多数元素【169】](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[LeetCode] 多数元素【169】

分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
![[001] [arm-cortex-m3/4] internal register](/img/49/a0eceac1a67267216dd9b2566033a1.jpg)
[001] [arm-cortex-m3/4] internal register

Oracle-PL/SQL编程
随机推荐
Oracle-PL/SQL编程
存储单位换算
【洛谷P1541】乌龟棋【DP】
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
[LeetCode] 反转字符串中的单词 III【557】
小鹏P7出事故,安全气囊未弹出,这正常吗?
Methods of adding styles to native JS
Using rendertext() to output multiple lines of text with rendertext() in R shiny
Market Research - current situation and future development trend of anterior cruciate ligament (ACL) reconstruction Market
高并发介绍及应对
杰理之如何测试按键的误触率【篇】
Market Research - current situation and future development trend of herringbone gear Market
手写ORM(对象关系映射)增删改查
NC24325 [USACO 2012 Mar S]Flowerpot
UE4 game architecture learning notes
位的高阶运算
uniapp微信登录返显用户名和头像
[LeetCode] 存在重复元素【217】
Jatpack------LiveData
Niuke: Dragon and dungeon games