当前位置:网站首页>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()
}
}
边栏推荐
猜你喜欢
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
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
Struct, bit segment, enumeration, union
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
Radis:Linux上安装Redis(步骤)
NC50965 Largest Rectangle in a Histogram
Baidu AI Cloud - create a face recognition application
Dynamic memory allocation (malloc calloc realloc free)
图形视图框架
位的高阶运算
随机推荐
Phpcms realizes the direct Alipay payment function of orders
Market Research - current market situation and future development trend of aircraft front wheel steering system
建立自己的网站(22)
Dahua cloud native load balancing article - the passenger flow of small restaurants has increased
杰理之内置短按再长按,不管长按多长时间都是短按【篇】
小鹏P7出事故,安全气囊未弹出,这正常吗?
Market Research - current situation and future development trend of cell-based seafood market
Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
540. Single element in ordered array
U++ 学习笔记 ----松弛
UE4 游戏架构 学习笔记
杰理之内置关机电流 1.2uA,之后不能长按开机【篇】
New feature of go1.18: trylock, which has been tossed n times
Market Research - current market situation and future development trend of total nutrition products
【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
Market Research - current situation and future development trend of carob chocolate market
杰理之如何测试按键的误触率【篇】
影视随摘
Perceptron model and Application
NC50965 Largest Rectangle in a Histogram