Go 并发秘籍:深入解析 sync.Once 的高效单例模式实现

sync.Once 作用

sync.Once 是 Go 语言标准库中的一个同步原语,用于确保在并发环境中某个操作只执行一次。它常用于初始化配置、建立数据库连接或创建单例对象等场景。

sync.Once 使用示例

以下是 sync.Once 的一个简单使用示例:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once

	for i := 1; i <= 10; i++ {
	i := i
		once.Do(func() {
			fmt.Println(i)
		})
	}
}

这段代码将输出 1,表明 sync.Once 确保了初始化函数只执行一次。

sync.Once 源码分析
Once 结构体定义

sync.Once 的结构体定义如下:

// 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.
type Once struct {
    done uint32
    m    Mutex
}
  • done 是一个用于标记是否已经执行过操作的字段。
  • m 是一个互斥锁,用于保证并发安全。

为什么 done 要放置在第一个变量?

done 作为第一个字段,是因为它是在“热路径”(hot path)中频繁访问的变量。热路径是指程序中经常执行的代码段。将 done 放在第一个字段,可以减少 CPU 指令,从而提升性能。这是因为访问结构体的第一个字段不需要计算偏移量,直接通过结构体指针即可访问。

实现函数

sync.OnceDo 方法实现如下:

// 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 {
        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()
    }
}
  • Do 方法首先检查 done 是否为 0,如果是,则调用 doSlow 方法。
    • 双重检查的思路
  • doSlow 方法首先获取互斥锁,然后再次检查 done 是否为 0,如果是,则执行传入的函数 f,并在函数执行完毕后将 done 设置为 1。
错误的实现方法

注释中提到了一个错误的实现示例:

if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
    f()
}

​ 这种方法的问题在于,它不保证 f 函数执行完毕后其他线程才能继续执行。这可能导致在 f 函数执行期间,其他线程认为初始化已完成而直接返回,从而获取到未完全初始化的对象。

结论

sync.Once 通过原子操作和互斥锁确保了初始化操作的线程安全性和唯一性。将 done 作为第一个字段可以优化性能,因为它减少了访问该字段所需的 CPU 指令。在设计并发控制机制时,应避免错误的实现,确保操作的原子性和可见性。

参考资料
  1. StackOverflow 上关于 “hot path” 的讨论
  2. 极客兔兔关于 Go sync.Once 的文章
  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值