文本介绍sync.Once的用法及实现原理。
Golang sync.Once实现让方法仅一次的对象。它是Go包内置的功能,角色与init函数类似,但也有差异:
当一个函数在程序启动后不想被多次执行,我们可以使用sync.Once。
首先从示例开始,看如何使用sync.Once:
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
onceBody := func() {
fmt.Println("Only once")
}
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
once.Do(onceBody)
done <- true
}()
}
for i := 0; i < 10; i++ {
<-done
}
}
输出结果:
Only once
下面通过源码解释实现原理.
sync.Once结构体仅包括两个属性,done记录执行状态,sync.Mutex和sync.atomic确保done变量的线程安全。
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
}
继续看其方法:
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.
/ / Equal to Return Done value
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()
}
}
sync.once 仅提供了一个Do()方法,其参数为待执行的函数,该函数的代码块期望仅被执行一次。下面看代码实现过程:
首先,atomic读取done字段值是否被改变,然后当如果没有改变时执行doSlow方法。当进入doSlow方法,开始执行锁操作,在并发环境下仅有一个线程被执行,然后基于done字段是否被改变执行待执行函数,如果没有改变则执行f函数。当代码块执行后,done字段被激活。
通过源码可以理解Once的原理,同时也了解Mutex和atomic的具体应用示例。