Thursday, October 30, 2025
HomeGolangSync.As soon as vs Singleton Initialisation - Technical Dialogue

Sync.As soon as vs Singleton Initialisation – Technical Dialogue


I’ve to get a single occasion of DB. For this I wrote the next code –

func getDb() map[string]int {
	if db == nil {
		lock.Lock()
		if db == nil {
			db = map[string]int{}
		}
		lock.Unlock()
	}
	return db
}

There may be one other manner to do that utilizing Sync.As soon as –

func (o *As soon as) Do(f func()) {
	if atomic.LoadUint32(&o.carried out) == 0 {
		o.doSlow(f)
	}
}
func (o *As soon as) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.carried out == 0 {
		defer atomic.StoreUint32(&o.carried out, 1)
		f()
	}
}

Which one ought to I exploit ?
Is the
atomic.LoadUint32(&o.carried out) == 0 computationally costly than db == nil ?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments