Golang sync.Once
1、概述
sync.Once 是 Golang package 中使方法只执行一次的对象实现,作用与 init 函数类似。但也有所不同。
- init 函数是在文件包首次被加载的时候执行,且只执行一次
- sync.Once是在代码运行中需要的时候执行,且只执行一次
当一个函数不希望程序在一开始的时候就被执行的时候,我们可以使用 sync.Once 。
2、使用示例
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" ) 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 } } |
输出:
1 | Only once |
3、源码分析
sync.Once 使用变量 done 来记录函数的执行状态,使用 sync.Mutex 和 sync.atomic 来保证线程安全的读取 done 。
1 2 3 4 5 6 7 8 9 | 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 } |
只有两个字段,字段done
用来标识代码块是否执行过,字段m
是一个互斥锁。
接下来我们一起来看一下代码实现:
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 | 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. // 等价于return done值 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()方法,该方法的参数是一个入参为空的函数,这个函数也就是我们想要执行一次的代码块。
接下来我们看一下代码流程:
首先原子性的读取done字段的值是否改变,没有改变则执行doSlow()方法。
一进入doslow()方法就开始执行加锁操作,这样在并发情况下可以保证只有一个线程会执行,再判断一次当前done字段是否发生改变(这里肯定有朋友会感到疑惑,为什么这里还要在判断一次flag?这里目的其实就是保证并发的情况下,代码块也只会执行一次,毕竟加锁是在doslow()方法内,不加这个判断的在并发情况下就会出现其他goroutine也能执行f()),如果未发生改变,则开始执行代码块,代码块运行结束后会对done字段做原子操作,标识该代码块已经被执行过了。
其他:原子操作请参考 Golang sync/atomic包——原子操作 这篇博文。
参考:https://blog.csdn.net/qq_39397165/article/details/113409507
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2019-02-28 ORA-12519: TNS:no appropriate service handler found 解决
2018-02-28 虚拟货币ICO是什么意思 看完秒懂
2017-02-28 w命令