当前位置:网站首页>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()
}
}边栏推荐
- Market Research - current market situation and future development trend of night vision goggles for pilots
- Using rendertext() to output multiple lines of text with rendertext() in R shiny
- Dynamic memory allocation (malloc calloc realloc free)
- Graphic view frame
- PHP optimizes SQL queries in foreach
- [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 environmental friendly fireworks Market
- Pointer - function pointer
- Introduction to database system Chapter 1 short answer questions - how was the final exam?
- UE4 game architecture learning notes
猜你喜欢
随机推荐
uniapp微信登录返显用户名和头像
U++ 原始内存 学习笔记
Unity publishes a method of webgl playing sound
数学建模——图与网络模型及方法(一)
数据库系统概论第一章简答题-期末考得怎么样?
Market Research - current situation and future development trend of cell-based seafood market
杰理之样机在多次触摸后会触发关机【篇】
杰理之修改不需要长按开机功能【篇】
傑理之修改不需要長按開機功能【篇】
Task and privilege level protection
[LeetCode] 存在重复元素【217】
phpcms实现订单直接支付宝支付功能
杰理之、产线装配环节【篇】
[LeetCode] 数组中的第K个最大元素【215】
wait解决僵尸进程
`${}`的用法
PMP项目整合管理
【洛谷P1541】乌龟棋【DP】
Golang的学习路线
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
![[LeetCode] 反转字符串中的单词 III【557】](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
![[foreign journal] sleep and weight loss](/img/81/42dcfae19e72a0bc761cb7a40fe5d5.jpg)





