当前位置:网站首页>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()
}
}边栏推荐
- [error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
- 钟薛高回应产品1小时不化:含固体成分 融化不能变成水
- Market Research - current situation and future development trend of environmental friendly fireworks Market
- Niuke: Dragon and dungeon games
- 牛客网:最大子矩阵
- 送给即将工作的自己
- [shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
- Market Research - current situation and future development trend of herringbone gear Market
- 大话云原生之负载均衡篇-小饭馆客流量变大了
- Market Research - current situation and future development trend of marine clutch Market
猜你喜欢

Graphic view frame

Simpleitk use - 3 Common operations

Utilisation de simpletk - 4. Question étrange

Perceptron model and Application

对象与对象变量
![[foreign journal] sleep and weight loss](/img/81/42dcfae19e72a0bc761cb7a40fe5d5.jpg)
[foreign journal] sleep and weight loss

大话云原生之负载均衡篇-小饭馆客流量变大了
![[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)

Dahua cloud native load balancing article - the passenger flow of small restaurants has increased

UE4 游戏架构 学习笔记
随机推荐
#include errors detected. Please update your includePath.
Market Research - current market situation and future development trend of handheld wound imaging equipment
百度智能云-创建人脸识别应用
Perceptron model and Application
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
How should programmers write logs
Market Research - current market situation and future development trend of aircraft wireless intercom system
Market Research - current situation and future development trend of preclinical medical device testing service market
性能优化----严苛模式
Wait to solve the zombie process
任务和特权级保护
UE4 UI自适应屏幕
What is the'function'keyword used in some bash scripts- What is the 'function' keyword used in some bash scripts?
存储单位换算
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
Mathematical modeling -- graph and network models and methods (I)
Jerry's modification does not require long press the boot function [chapter]
uniapp微信登录返显用户名和头像
悬镜安全在RSAC2022上斩获Global InfoSec Awards四项大奖
UE4 游戏架构 学习笔记