当前位置:网站首页>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()
}
}边栏推荐
- Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
- [QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
- 影视随摘
- 分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
- I admire that someone explained such an obscure subject as advanced mathematics so easily
- Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
- 世界环境日 | 周大福用心服务推动减碳环保
- Market Research - current situation and future development trend of herringbone gear Market
- New feature of go1.18: trylock, which has been tossed n times
- 大话云原生之负载均衡篇-小饭馆客流量变大了
猜你喜欢

Oracle-PL/SQL编程

Utilisation de simpletk - 4. Question étrange

Build your own website (22)

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
![NC24325 [USACO 2012 Mar S]Flowerpot](/img/cf/86acbcb524b3af0999ce887c877781.png)
NC24325 [USACO 2012 Mar S]Flowerpot

Graphic view frame

SimpleITK使用——3. 常见操作

Mathematical modeling -- graph and network models and methods (I)
![[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)](/img/4c/c8dae41fc2eb18b5153cf36861fc7d.jpg)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)

Jatpack------LiveData
随机推荐
NC50965 Largest Rectangle in a Histogram
杰理之内置短按再长按,不管长按多长时间都是短按【篇】
牛客网:最大子矩阵
[micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
Golang面试整理 三 简历如何书写
杰理之如何测试按键的误触率【篇】
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
Methods of adding styles to native JS
PHP optimizes SQL queries in foreach
Simpleitk use - 4 Strange question
U++ learning note pile
Market Research - current situation and future development trend of anti-counterfeiting label market
Using rendertext() to output multiple lines of text with rendertext() in R shiny
Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
Dynamic memory allocation (malloc calloc realloc free)
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
Hanoi Tower problem
Film and television excerpts
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
Socket套接字C/S端流程