当前位置:网站首页>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()
}
}
边栏推荐
- wait解决僵尸进程
- Film and television excerpts
- [shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
- PHP implements querying the data matching the date of birth according to the entered age
- Market Research - current market situation and future development trend of intravenous injection (IV) bottles
- Socket套接字C/S端流程
- 杰理之、产线装配环节【篇】
- Phpcms realizes the direct Alipay payment function of orders
- UE4 game architecture learning notes
- Utilisation de simpletk - 4. Question étrange
猜你喜欢
随机推荐
Market Research - current market situation and future development trend of marine wet exhaust hose
Market Research - current situation and future development trend of herringbone gear Market
PHP微信抢红包的算法
Unity发布WebGL播放声音的一种方法
[LeetCode] 存在重复元素【217】
Market Research - current market situation and future development trend of high tibial osteotomy plate
Market Research - current situation and future development trend of sickle cell therapy Market
wait解决僵尸进程
Technological Entrepreneurship: failure is not success, but reflection is
钟薛高回应产品1小时不化:含固体成分 融化不能变成水
Market Research - current market situation and future development trend of intravenous injection (IV) bottles
杰理之直接触摸样机的顶针反应不正常【篇】
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
php优化foreach中的sql查询
Market Research - current market situation and future development trend of aircraft wireless intercom system
世界环境日 | 周大福用心服务推动减碳环保
NC24325 [USACO 2012 Mar S]Flowerpot
Radis:Linux上安装Redis(步骤)
Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed