当前位置:网站首页>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()
}
}边栏推荐
- 手写ORM(对象关系映射)增删改查
- Market Research - current situation and future development trend of anti-counterfeiting label market
- 【洛谷P1541】乌龟棋【DP】
- Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
- 数学建模——图与网络模型及方法(一)
- Market Research - current situation and future development trend of environmental friendly fireworks Market
- Oracle cursor
- 'when to use const char * and when to use const char []' - when to use const char * and when to use const char []
- Golang的学习路线
- Socket socket c/s end process
猜你喜欢
![[001] [arm-cortex-m3/4] internal register](/img/49/a0eceac1a67267216dd9b2566033a1.jpg)
[001] [arm-cortex-m3/4] internal register

数组进阶提高
![[shutter] shutter application theme (themedata | dynamic modification theme)](/img/77/6b0082368943aee7108ac550141f28.gif)
[shutter] shutter application theme (themedata | dynamic modification theme)

Objects and object variables

Oracle cursor
![[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)](/img/27/8594ba0b49d5008b7469967babed17.jpg)
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)

小鹏P7出事故,安全气囊未弹出,这正常吗?

540. Single element in ordered array

wait解决僵尸进程
![[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)](/img/07/6f2dfb543cb0ab4f27169da7e6ad07.jpg)
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
随机推荐
New feature of go1.18: trylock, which has been tossed n times
Market Research - current market situation and future development trend of handheld wound imaging equipment
SimpleITK使用——4. 奇怪的問題
Objects and object variables
Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
U++ learning note pile
PHP微信抢红包的算法
[foreign journal] sleep and weight loss
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
Oracle-PL/SQL编程
【AUTOSAR-DCM】-4.3-UDS $22和$2E服务如何读取和写入NVM数据
Source code analysis - lightweight asynchronous crawler framework Ruia
[autosar-dcm] - 4.3-how UDS $22 and $2e services read and write NVM data
[LeetCode] 回文数【9】
高并发介绍及应对
Phpcms realizes the direct Alipay payment function of orders
Methods of adding styles to native JS
全面解析分享购商业模式逻辑?分享购是如何赋能企业
JS获取display为none的隐藏元素的宽度和高度的解决方案
Dahua cloud native load balancing article - the passenger flow of small restaurants has increased