sync.Once 是 Golang package 中使方法只执行一次的对象实现,作用与 init 函数类似。但也有所不同。
当一个函数不希望程序在一开始的时候就被执行的时候,我们可以使用 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
}
}
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var once sync.Once
onceBody := func() {
fmt.Println("Only once")
}
for i:=0; i<10; i++ {
go func() {
once.Do(onceBody)
}()
}
time.Sleep(time.Second*2)
}
输出:
sync.Once 使用变量 done 来记录函数的执行状态,使用 sync.Mutex 和 sync.atomic 来保证线程安全的读取 done 。
核心思想是使用原子计数记录被执行的次数。使用Mutex Lock Unlock锁定被执行函数,防止被重复执行。
源码
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sync
import (
"sync/atomic"
)
// Once is an object that will perform exactly one action.
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/x86),
// and fewer instructions (to calculate offset) on other architectures.
done uint32
m Mutex
}
// 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()) {
// 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.
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()
}
}
例子:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
once := &sync.Once{
}
go do(once)
go do(once)
time.Sleep(time.Second*2)
}
func do(once *sync.Once){
fmt.Println("Start do")
once.Do(func() {
fmt.Println("Doing something...")
})
fmt.Println("Do end")
}
输出:这里 Doing something 只被调用了一次。
或者:
sync.once是被用于全局执行单次函数的场景,用法比较简单。
我们用到它主要是为了单元测试的执行,因为有些单元测试的函数需要和db交互,还有log的初始化,config配置文件的初始化,等等,这些其实都只需要执行一次就够了,对于单元测试来说,如何知道这些是否执行过呢,那就用sync.once,这样我就不需要关心这些是否重复执行,只要在每个用例的最前面执行sync.once的方法就行了。
示例:
var InitOnce sync.Once
func DbInitOnce() {
connect_str := config.Gconfig.DB.UserName + ":" + config.Gconfig.DB.Password + "@tcp(" +
config.Gconfig.DB.IP + ":" + config.Gconfig.DB.Port + ")/" + config.Gconfig.DB.Name
Gdb.Db, _ = sqlx.Open("mysql", connect_str)
_ = Gdb.Db.Ping()
Gdb.Db.SetMaxOpenConns(config.Gconfig.DB.MaxConn)
Gdb.Db.SetMaxIdleConns(200)
Gdb.Db.SetConnMaxLifetime(time.Second * 300)
}
var loggerOnce sync.Once
var configOnce sync.Once
func loggerInit() {
logger.New(config.Gconfig.Log.LogFileName)
logger.SetDefaultLogger(config.Gconfig.Log.LogFileName).SetLevel(config.Gconfig.Log.LogLevel)
}
func configInit() {
config.ReadConfigFileForTest(&config.Gconfig, "../config.cfg")
}
func TestInsertIndex(t *testing.T) {
//单元测试用例
configOnce.Do(configInit)
loggerOnce.Do(loggerInit)
db.InitOnce.Do(db.DbInitOnce) //第一段代码
Db2.Db = db.Gdb.Db
convey.Convey("测试插入汇率", t, func() {
convey.Convey("插入无报错", func() {
var testEntity = IndexDetail{
Currency: "USD",
Date: "2018-03-22",
Index: 0.8058,
}
err := Db2.insertIndex(testEntity)
convey.So(err, convey.ShouldBeNil)
})
})
}