当前位置:网站首页>go 4种单例模式
go 4种单例模式
2022-07-02 22:07: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()
}
}
边栏推荐
- Regular expression (2)
- SimpleITK使用——4. 奇怪的问题
- U++ learning note pile
- UE4 UI自适应屏幕
- Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
- [QT] QT multithreading development - four methods to realize multithreading design
- 杰理之直接触摸样机的顶针反应不正常【篇】
- JS solution for obtaining the width and height of hidden elements whose display is none
- Pointer - function pointer
- Pointer and string
猜你喜欢
Jatpack------LiveData
Source code analysis - lightweight asynchronous crawler framework Ruia
Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
Oracle PL / SQL programming
#include errors detected. Please update your includePath.
PMP项目整合管理
[foreign journal] sleep and weight loss
Struct, bit segment, enumeration, union
Socket套接字C/S端流程
Oracle-PL/SQL编程
随机推荐
Market Research - current market situation and future development trend of aircraft wireless intercom system
《乔布斯传》英文原著重点词汇笔记(九)【 chapter seven】
New feature of go1.18: trylock, which has been tossed n times
SimpleITK使用——4. 奇怪的問題
Pointer array parameter passing, pointer parameter passing
PHP implements querying the data matching the date of birth according to the entered age
#include errors detected. Please update your includePath.
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
[001] [arm-cortex-m3/4] internal register
phpcms实现订单直接支付宝支付功能
Simpleitk use - 3 Common operations
数学建模——图与网络模型及方法(一)
Market Research - current situation and future development trend of preclinical medical device testing service market
Market Research - current situation and future development trend of carob chocolate market
[LeetCode] 多数元素【169】
Market Research - current market situation and future development trend of aircraft front wheel steering system
Learn computer knowledge from scratch
Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
uniapp微信登录返显用户名和头像
Technological Entrepreneurship: failure is not success, but reflection is