【go实战系列一】开篇:在循环中重新定义变量(redefining for loop variable semantics)
【go实战系列二】关于切片的基本操作 copy sort append 快速复制 排序 删除操作
【go实战系列三】关于切片的基本操作 copy sort append 快速复制 排序 删除操作
【go实战系列四】go语言中 Hot path 热路径 可能你从没听过 却如此重要
这是根据go在项目实战中,作者发掘的问题与技巧,希望能与所有的gopher一起分享,一起成长,如果文章有错误,也请大家及时指正问题,作者会立刻修改
sync.Once
是 Go 标准库提供的使函数只执行一次的实现,常应用于单例模式,例如初始化配置、保持数据库连接等。作用与 init 函数类似,但有区别。
init 函数
是当所在的 package 首次被加载时执行,若迟迟未被使用,则既浪费了内存,又延长了程序加载时间。
sync.Once 可以在代码的任意位置初始化和调用,因此可以延迟到使用时再执行,并发场景下是线程安全的。
在多数情况下,sync.Once 被用于控制变量的初始化,这个变量的读写满足如下三个条件:
第一:保证变量仅被初始化一次,需要有个标志来判断变量是否已初始化过,若没有则需要初始化。
第二:线程安全,支持并发,无疑需要互斥锁来实现。
go-sdk 实现源码如下:
package syncimport ("sync/atomic"
)type Once struct {done uint32m Mutex
}func (o *Once) Do(f func()) {if atomic.LoadUint32(&o.done) == 0 {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 的实现与一开始的猜测是一样的,使用 done 标记是否已经初始化,使用锁 m Mutex 实现线程安全。
字段 done 的注释也非常值得一看:
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 uint32m Mutex
}
其中解释了为什么将 done 置为 Once 的第一个字段:done 在热路径中,done 放在第一个字段,能够减少 CPU 指令,也就是说,这样做能够提升性能。
package mainimport ("fmt"
)type student struct {name stringage int
}func main() {p1 := &student{name: "123",age: 123,}fmt.Printf("%p \n", p1)fmt.Printf("%p \n", &p1.name)fmt.Printf("%p \n", &p1.age)
}
打印结果:
0xc000008078
0xc000008078
0xc000008088
热路径(hot path)是程序非常频繁执行的一系列指令,sync.Once 绝大部分场景都会访问 o.done,在热路径上是比较好理解的,如果 hot path 编译后的机器码指令更少,更直接,必然是能够提升性能的。
为什么放在第一个字段就能够减少指令呢?
因为结构体第一个字段的地址和结构体的指针是相同的
,如果是第一个字段,直接对结构体的指针解引用即可。如果是其他的字段,除了结构体指针外,还需要计算与第一个值的偏移(calculate offset)。在机器码中,偏移量是随指令传递的附加值,CPU 需要做一次偏移值与指针的加法运算,才能获取要访问的值的地址。因为,访问第一个字段的机器代码更紧凑,速度更快。
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 uint32m Mutex
}
欢迎大家在评论区指出这个问题的答案
参考:What does “hot path” mean in the context of sync.Once?
希望对大家能够有帮助
上一篇:微信小程序关联组件