sync.Once表示只执行一次函数。要做到这点,就需要两点: (1)计数器,统计函数执行次数; (2)线程安全,保障在多G情况下,函数仍然只执行一次,比如锁。
import (
"sync/atomic"
)
// Once is an object that will perform exactly one action.
type Once struct {
m Mutex
done uint32
}
Once结构体证明了之前的猜想,果然有两个变量。
// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
// var once Once
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
// config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
//
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 1 {
return
}
// Slow-path.
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
Do方法相当简单,但是也是有可以学习的地方。比如一些标志位可以通过原子操作表示,避免加锁,提高性能。Do方法实现过程如下: (1)首先原子load函数执行次数,如果已经执行过了,就return; (2)lock; (3)执行函数; (4)原子store函数执行次数1; (5)unlock。
package main
import (
"fmt"
"sync"
"time"
)
var once sync.Once
var onceBody = func() {
fmt.Println("Only once")
}
func main() {
for i := 0; i < 10; i++ {
go func(i int) {
once.Do(onceBody)
fmt.Println("i=",i)
}()
}
time.Sleep(time.Second) //睡眠1s用于执行go程,注意睡眠时间不能太短
}
程序运行输出:
Only once
i= 3
i= 6
i= 4
i= 5
i= 7
i= 0
i= 1
i= 2
i= 9
i= 8
从输出结果可以看出,尽管for循环每次都会调用once.Do()方法,但是函数onceBody()却只会被执行一次。