Golang里的变量延迟加载
延迟加载,只在需要的时候初始化变量,同时需要防止重复的初始化变量,这可以节省不必要的变量初始化时间和空间(如果程序根本用不到此变量,就不会初始化它)
以下代码来自 Gin
import (
"html/template"
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
// 定义一个 sync.Once 变量
var once sync.Once
var internalEngine *gin.Engine
func engine() *gin.Engine {
//执行,并且只执行一次初始化操作
once.Do(func() {
internalEngine = gin.Default()
})
return internalEngine
}
// 后续其它要用到变量 internalEngine 的地方,都通过 engine() 方法来间接访问
func LoadHTMLGlob(pattern string) {
engine().LoadHTMLGlob(pattern)
}
// 后续其它要用到变量 internalEngine 的地方,都通过 engine() 方法来间接访问
func LoadHTMLFiles(files ...string) {
engine().LoadHTMLFiles(files...)
}
此方案的原理,是 sync.Once 里有一个原子性的操作,里面有个变量用来原子性的记录操作次数,
如果从未调用过,此变量为0,如果调用过一次,将其设置为1
下次再调用,因为变量是1了,下次调用将被忽略
此内部变量的操作是原子性的
以下是 sync.Once 的实现代码:
// Once is an object that will perform exactly one action.
//
// A Once must not be copied after first use.
//
// In the terminology of the Go memory model,
// the return from f “synchronizes before”
// the return from any call of once.Do(f).
type Once struct {
// done indicates whether the action has been performed.
// It is first in the struct because it is used in the hot path.
// The hot path is inlined at every call site.
// Placing done first allows more compact instructions on some architectures (amd64/386),
// and fewer instructions (to calculate offset) on other architectures.
done uint32
m Mutex
}
// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
//
// var once Once
//
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
//
// config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
func (o *Once) Do(f func()) {
// Note: Here is an incorrect implementation of Do:
//
// if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
// f()
// }
//
// Do guarantees that when it returns, f has finished.
// This implementation would not implement that guarantee:
// given two simultaneous calls, the winner of the cas would
// call f, and the second would return immediately, without
// waiting for the first's call to f to complete.
// This is why the slow path falls back to a mutex, and why
// the atomic.StoreUint32 must be delayed until after f returns.
if atomic.LoadUint32(&o.done) == 0 {
// Outlined slow-path to allow inlining of the fast-path.
o.doSlow(f)
}
}
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}