当前位置:网站首页>Go four singleton modes
Go four singleton modes
2022-07-02 22:50:00 【Give me a bottle of Borneol】
Slacker type —— Non-thread safety
Non-thread safety , It means that multiple objects may be created under multithreading .
// Use structs instead of classes
type Tool struct {
values int
}
// Create private variables
var instance *Tool
// Methods to get singleton objects , Reference passing returns
func GetInstance() *Tool {
if instance == nil {
instance = new(Tool)
}
return instance
}
On a non thread safe basis , utilize Sync.Mutex Lock to ensure thread safety , However, every time this method is called, a lock operation is performed , Not very efficient in performance
// Lock object
var lock sync.Mutex
// Lock to ensure thread safety
func GetInstance() *Tool {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = new(Tool)
}
return instance
}
Hungry Chinese style
Create objects directly , There is no need to judge that it is empty , It is also thread safe , The only drawback is that the object is created at the same time as the package is imported , And continue to occupy the memory .
Go Language hungry Chinese style can be used init function , You can also use global variables .
type cfg struct {
}
var cfg *config
func init() {
cfg = new(config)
}
// NewConfig Provides a method to get an instance
func NewConfig() *config {
return cfg
}
type config struct {
}
// Global variables
var cfg *config = new(config)
// NewConfig Provides a method to get an instance
func NewConfig() *config {
return cfg
}
Double check
In the lazy style ( Thread safety ) On the basis of the optimization , Reduce the operation of locking , Ensure thread safety without affecting performance .
// Lock object
var lock sync.Mutex
// The first judgment is not locked , The second locking ensures thread safety , Once the object is created , There is no need to lock the object .
func GetInstance() *Tool {
if instance == nil {
lock.Lock()
if instance == nil {
instance = new(Tool)
}
lock.Unlock()
}
return instance
}
sync.Once
adopt sync.Once To ensure that the object creation method is executed only once
var once sync.Once
func GetInstance() *Tool {
once.Do(func() {
instance = new(Tool)
})
return instance
}
sync.Once Internal is also a way of double inspection in essence , But in terms of writing, it will be more concise than writing double check by yourself , Here are Once Source code
func (o *Once) Do(f func()) {
// Determine whether the method has been implemented , If it has been executed, it will not be executed
if atomic.LoadUint32(&o.done) == 1 {
return
}
// Slow-path.
o.m.Lock()
defer o.m.Unlock()
// To lock , Make another judgment , If not implemented , Then mark that the line has been scanned and call the method
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
边栏推荐
- 《乔布斯传》英文原著重点词汇笔记(十一)【 chapter nine】
- 任务和特权级保护
- SimpleITK使用——3. 常见操作
- [shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
- 高并发介绍及应对
- Market Research - current situation and future development trend of preclinical medical device testing service market
- Market Research - current market situation and future development trend of aircraft wireless intercom system
- Market Research - current situation and future development trend of herringbone gear Market
- U++ 学习笔记 堆
- 用sentinel熔断比例阈值改不了,设置慢调用比例没效果
猜你喜欢
Struct, bit segment, enumeration, union
Perceptron model and Application
Socket套接字C/S端流程
Dynamic memory allocation (malloc calloc realloc free)
【外刊】睡眠与减肥
位的高阶运算
NC24325 [USACO 2012 Mar S]Flowerpot
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
Mathematical modeling -- graph and network models and methods (I)
Phpcms realizes the direct Alipay payment function of orders
随机推荐
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
Niuke: Dragon and dungeon games
Commodity information management system (C language document version)
杰理之充电拔出,无法触摸开机【篇】
[micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
杰理之如何测试按键的误触率【篇】
Simpleitk use - 3 Common operations
Market Research - current situation and future development trend of sickle cell therapy Market
NC24325 [USACO 2012 Mar S]Flowerpot
Additional: [login information storage] and [login status verification]; (including: summarizing all the contents of [login information storage] and [login status verification] so far;)
图形视图框架
Socket socket c/s end process
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
影视随摘
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
Oracle PL / SQL programming
New feature of go1.18: introduce new netip Network Library
《乔布斯传》英文原著重点词汇笔记(十一)【 chapter nine】
建立自己的网站(22)