手撕 golang 中的单例模式——sync.Once 源码解析

74 阅读2分钟

sync.Once 时 Go 官方提供的用于支持实现单例模式的标准库工具

数据结构

// Once is an object that will perform exactly one action.
//
// A Once must not be copied after first use.
//
// In the terminology of the Go memory model,
// the return from f “synchronizes before”
// the return from any call of once.Do(f).
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 atomic.Uint32
	m    Mutex
}
  • sync.Once 的实现类中包含两个核心字段

    done 一个整数类型的 uint32 ,用于标识用户传入的任务函数是否已经被执行

    m 互斥锁 sync.Mutex ,用于保护标识值,避免由于并发读写导致数据不一致的情况

方法

// 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 o.done.CompareAndSwap(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 o.done.Store must be delayed until after f returns.

	if o.done.Load() == 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.Load() == 0 {
		defer o.done.Store(1)
		f()
	}
}

Untitled.png

  • sync.once 也是基于 double check 机制实现对全局任务单次执行的保证
    1. 检查 Once.Done 的值是否为 0,由于此处的 Done 采用的是 atomic.uint32 , 因此在这里避免了繁重的加锁动作
    2. 如果不为 0 则证明该任务已被执行
    3. 如果为 0,则进行加锁操作
    4. Once.Done 的值进行第二次检测,确保在竞争锁期间 Once.Done 的值为发生改变,即该任务未执行
    5. 执行任务并解锁