当前位置:网站首页>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()
}
}边栏推荐
- I admire that someone explained such an obscure subject as advanced mathematics so easily
- Oracle-游标
- [micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
- U++ learning notes - relaxation
- 杰理之样机无触摸,拆机之后重新安装变正常【篇】
- #include errors detected. Please update your includePath.
- `${}`的用法
- Oracle cursor
- 附加:【登录信息存储】与【登录状态校验】;(包括:总结了到目前为止,有关【登录信息存储】与【登录状态校验】的所有内容;)
- [shutter] shutter resource file use (import resource pictures | use image resources)
猜你喜欢
![[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')](/img/02/67448df1817e8b34b654722df8ecd4.jpg)
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')

大话云原生之负载均衡篇-小饭馆客流量变大了

Mathematical modeling -- graph and network models and methods (I)

Baidu AI Cloud - create a face recognition application

UE4 游戏架构 学习笔记

Socket socket c/s end process

wait解决僵尸进程

Oracle PL / SQL programming

NC50965 Largest Rectangle in a Histogram
![Additional: [login information storage] and [login status verification]; (including: summarizing all the contents of [login information storage] and [login status verification] so far;)](/img/b7/0f543829b57cf2f2544efec4910c17.png)
Additional: [login information storage] and [login status verification]; (including: summarizing all the contents of [login information storage] and [login status verification] so far;)
随机推荐
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
Regular expression (2)
I admire that someone explained such an obscure subject as advanced mathematics so easily
Socket socket c/s end process
数据库系统概论第一章简答题-期末考得怎么样?
Market Research - current market situation and future development trend of high tibial osteotomy plate
【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
Utilisation de simpletk - 4. Question étrange
Pointer - function pointer
PHP implements querying the data matching the date of birth according to the entered age
数学建模——图与网络模型及方法(一)
任务和特权级保护
Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens
PMP项目整合管理
杰理之如何测试按键的误触率【篇】
Golang面试整理 三 简历如何书写
基于ASP.net的手机销售管理系统(二手手机销售管理系统)+ASP.NET+C#语言+VS2010+数据库可以用于课设、毕设学习
NC50965 Largest Rectangle in a Histogram
Necessary browser plug-ins for network security engineers