Skip to content

Commit

Permalink
fix:sync.Once usage
Browse files Browse the repository at this point in the history
  • Loading branch information
keepchen committed Feb 4, 2024
1 parent 258281e commit 9b0069f
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 8 deletions.
7 changes: 5 additions & 2 deletions constants/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ type errorCodeTypeMsgMap struct {
maps map[LanguageCode]map[ICodeType]string
}

var ctm *errorCodeTypeMsgMap
var (
ctm *errorCodeTypeMsgMap
once sync.Once
)

// RegisterCode 注册常量代码
//
Expand All @@ -30,7 +33,7 @@ func RegisterCode(language LanguageCode, i18nMsg map[ICodeType]string) {
}

func init() {
(&sync.Once{}).Do(func() {
once.Do(func() {
ctm = &errorCodeTypeMsgMap{
mux: &sync.RWMutex{},
maps: make(map[LanguageCode]map[ICodeType]string),
Expand Down
3 changes: 2 additions & 1 deletion http/middleware/prometheusexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ func (r responseBodyWriter) Write(b []byte) (int, error) {
}

var (
once sync.Once
metricsSummaryVecLatency *prometheus.SummaryVec
metricsSummaryVecHttpStatus *prometheus.SummaryVec
)

func init() {
(&sync.Once{}).Do(func() {
once.Do(func() {
svl := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "api_durations",
Help: "[api] http latency distributions (milliseconds)",
Expand Down
7 changes: 5 additions & 2 deletions lib/cache/localkv.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ type localCache struct {
maps map[string]*localCacheValue
}

var lc *localCache
var (
lc *localCache
once sync.Once
)

func init() {
(&sync.Once{}).Do(func() {
once.Do(func() {
lc = &localCache{
mux: &sync.Mutex{},
maps: make(map[string]*localCacheValue),
Expand Down
10 changes: 7 additions & 3 deletions schedule/schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,14 @@ type taskJobPool struct {

var taskSchedules *taskJobPool

var cronJob *cron.Cron
var (
cronJob *cron.Cron
cronStartOnce sync.Once
initOnce sync.Once
)

func init() {
(&sync.Once{}).Do(func() {
initOnce.Do(func() {
taskSchedules = &taskJobPool{
mux: &sync.RWMutex{},
pool: make(map[string]*taskJob),
Expand Down Expand Up @@ -241,7 +245,7 @@ func (j *taskJob) run() {
//
// +------------------------- minute (0 - 59)
func (j *taskJob) RunAt(crontabExpr string) (cancel CancelFunc) {
(&sync.Once{}).Do(func() {
cronStartOnce.Do(func() {
cronJob = cron.New()
cronJob.Start()
})
Expand Down

0 comments on commit 9b0069f

Please sign in to comment.