我是靠谱客的博主 欣喜白猫,这篇文章主要介绍Golang sync.Once 简介与用法1.简介2.延迟初始化参考文献,现在分享给大家,希望可以做个参考。

在这里插入图片描述

文章目录

  • 1.简介
  • 2.延迟初始化
  • 参考文献

1.简介

sync.Once用来保证函数只执行一次。要达到这个效果,需要做到两点:
(1)计数器,统计函数执行次数;
(2)线程安全,保障在多 Go 程的情况下,函数仍然只执行一次,比如锁。

复制代码
1
2
3
4
5
6
7
8
9
10
import ( "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
23
package 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
7
Only 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
12
type 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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部