use sync.Once to replace lock (#5710)

* use atomic operation to optimize performance

* use sync.Once to replace lock
This commit is contained in:
luxcgo 2024-10-05 22:43:21 +08:00 committed by GitHub
parent cbfbf97af1
commit 0654bff7d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -24,11 +24,10 @@ import (
// ModelCache info collection // ModelCache info collection
type ModelCache struct { type ModelCache struct {
sync.RWMutex // only used outsite for bootStrap
orders []string orders []string
cache map[string]*ModelInfo cache map[string]*ModelInfo
cacheByFullName map[string]*ModelInfo cacheByFullName map[string]*ModelInfo
done bool bootstrapOnce *sync.Once
} }
// NewModelCacheHandler generator of ModelCache // NewModelCacheHandler generator of ModelCache
@ -36,6 +35,7 @@ func NewModelCacheHandler() *ModelCache {
return &ModelCache{ return &ModelCache{
cache: make(map[string]*ModelInfo), cache: make(map[string]*ModelInfo),
cacheByFullName: make(map[string]*ModelInfo), cacheByFullName: make(map[string]*ModelInfo),
bootstrapOnce: new(sync.Once),
} }
} }
@ -93,22 +93,20 @@ func (mc *ModelCache) Set(table string, mi *ModelInfo) *ModelInfo {
// Clean All model info. // Clean All model info.
func (mc *ModelCache) Clean() { func (mc *ModelCache) Clean() {
mc.Lock()
defer mc.Unlock()
mc.orders = make([]string, 0) mc.orders = make([]string, 0)
mc.cache = make(map[string]*ModelInfo) mc.cache = make(map[string]*ModelInfo)
mc.cacheByFullName = make(map[string]*ModelInfo) mc.cacheByFullName = make(map[string]*ModelInfo)
mc.done = false mc.bootstrapOnce = new(sync.Once)
} }
// Bootstrap Bootstrap for models // Bootstrap Bootstrap for models
func (mc *ModelCache) Bootstrap() { func (mc *ModelCache) Bootstrap() {
mc.Lock() mc.bootstrapOnce.Do(func() {
defer mc.Unlock() mc.bootstrap()
if mc.done { })
return }
}
func (mc *ModelCache) bootstrap() {
var ( var (
err error err error
models map[string]*ModelInfo models map[string]*ModelInfo
@ -310,7 +308,6 @@ end:
fmt.Println(err) fmt.Println(err)
debug.PrintStack() debug.PrintStack()
} }
mc.done = true
} }
// Register Register models to model cache // Register Register models to model cache