Golang sync.Once详解

文本介绍sync.Once的用法及实现原理。

Golang sync.Once实现让方法仅一次的对象。它是Go包内置的功能,角色与init函数类似,但也有差异:

  • init函数是当文件被加载时执行,仅执行一次
  • sync.Once当代码需要被执行时执行,但也仅执行一次

当一个函数在程序启动后不想被多次执行,我们可以使用sync.Once。

示例

首先从示例开始,看如何使用sync.Once:

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
    }
}

输出结果:

Only once

下面通过源码解释实现原理.

源码分析

sync.Once结构体仅包括两个属性,done记录执行状态,sync.Mutex和sync.atomic确保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/386),
    // and fewer instructions (to calculate offset) on other architectures.
    done uint32
    m    Mutex
}

继续看其方法:

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.
        / / Equal to Return Done value
    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()方法,其参数为待执行的函数,该函数的代码块期望仅被执行一次。下面看代码实现过程:

首先,atomic读取done字段值是否被改变,然后当如果没有改变时执行doSlow方法。当进入doSlow方法,开始执行锁操作,在并发环境下仅有一个线程被执行,然后基于done字段是否被改变执行待执行函数,如果没有改变则执行f函数。当代码块执行后,done字段被激活。

总结

通过源码可以理解Once的原理,同时也了解Mutex和atomic的具体应用示例。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值