文章目录
- 1.简介
- 2.延迟初始化
- 参考文献
1.简介
sync.Once
用来保证函数只执行一次。要达到这个效果,需要做到两点:
(1)计数器,统计函数执行次数;
(2)线程安全,保障在多 Go 程的情况下,函数仍然只执行一次,比如锁。
1
2
3
4
5
6
7
8
9
10import ( "sync/atomic" ) // Once is an object that will perform exactly one action. type Once struct { m Mutex done uint32 }
Once 结构体证明了之前的猜想,果然有两个变量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31// 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。
下面看一个示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package main import ( "fmt" "sync" "time" ) var once sync.Once var onceBody = func() { fmt.Println("Only once") } func main() { for i := 0; i < 5; i++ { go func(i int) { once.Do(onceBody) fmt.Println("i=",i) }(i) } time.Sleep(time.Second) // 睡眠 1s 等待 go 程执行完,注意睡眠时间不能太短。 }
程序运行输出:
1
2
3
4
5
6
7Only once i= 3 i= 4 i= 0 i= 1 i= 2
从输出结果可以看出,尽管 for 循环每次都会调用 once.Do() 方法,但是函数 onceBody() 却只会被执行一次。
2.延迟初始化
利用 sync.Once 只执行一次的特性,可以轻松实现延迟初始化。
有些初始化操作,如果不希望程序在一开始的时候就被执行的时候,我们可以使用 sync.Once 在需要的时候才进行初始化。
比如 get 一个客户端对象。
1
2
3
4
5
6
7
8
9
10
11
12type MyClient struct{} var once sync.Once var myCli *MyClient func getMyClient() *MyClient { once.Do(func() { myCli = new(MyClient) }) return myCli }
在需要获取 MyClient 的对象时,不需要在程序在一开始的时候去初始化,而是在真正使用的时候直接调用 getMyClient 函数即可获取。
聪明的你可能已经发现,上面的初始化写法实际上是 Go 单例模式的一种实现方式。
参考文献
简书.Go语言——sync.Once分析
Package sync.Go 编程语言官网
最后
以上就是欣喜白猫最近收集整理的关于Golang sync.Once 简介与用法1.简介2.延迟初始化参考文献的全部内容,更多相关Golang内容请搜索靠谱客的其他文章。
发表评论 取消回复