当前位置:网站首页>Important knowledge of golang: sync Once explanation

Important knowledge of golang: sync Once explanation

2022-06-23 15:24:00 yue_ xin_ tech

sync.Once Introduce

As mentioned before Go Concurrent helper for :WaitGroup. alike , sync.Once It's also Go An official concurrency helper , It enables functional methods to execute only once , To achieve a similar init The effect of the function . Let's take a brief look at its usage :

func main() {
    
	var once sync.Once
	onceFunc := func() {
    
		fmt.Println("Only once")
	}

	for i := 0; i < 10; i++ {
    
		once.Do(onceFunc)
	}
}

After execution here, we will only see once Only once Print information for , This is it. sync.Once One time effect of .

sync.Once Source code

Let's see sync.Once Source code :

type Once struct {
	done uint32
	m    Mutex
}

func (o *Once) Do(f func()) {
    //  Atomic load identification value , Judge whether it has been executed 
	if atomic.LoadUint32(&o.done) == 0 { 
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) { //  I haven't executed a function yet 
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 { //  Determine again whether the function has been executed 
		defer atomic.StoreUint32(&o.done, 1) //  Atomic manipulation : Modify the identification value 
		f() //  Execute function 
	}
}

It can be concluded from the above that ,sync.Once Is through the identification of a value , Atomic modification and loading , To reduce lock competition .


Interested friends can search the official account 「 Read new technology 」, Pay attention to more push articles .
If you can , Just like it by the way 、 Leave a message 、 Under the share , Thank you for your support !
Read new technology , Read more new knowledge .
 Read new technology

原网站

版权声明
本文为[yue_ xin_ tech]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231438381153.html

随机推荐