golang sync.once解析

清晨的麦田 · · 218 次点击 · · 开始浏览    

实现原理(当前代码版本go version go1.11.4 )

1.atomic 原子操作计数器,用于记录此Once对象下的done的值,func()方法只执行一次


// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sync

import (

// Once is an object that will perform exactly one action.
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 uint32
    m    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 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 {
        // Outlined slow-path to allow inlining of the fast-path.

func (o *Once) doSlow(f func()) {
    defer o.m.Unlock()
    if o.done == 0 {
        defer atomic.StoreUint32(&o.done, 1)

golang中sync包中的sync.Once.Do(f func())用于只执行一次的 func()方法,Mutex互斥锁的实现本章不做探讨


package main

import (

type SliceNum []int

func NewSlice() SliceNum {
    return make(SliceNum, 0)


func (s *SliceNum) Add(elem int) *SliceNum {
    *s = append(*s, elem)
    fmt.Println("add", elem)
    fmt.Println("add SliceNum end", s)
    return s
func (s *SliceNum) test(elem int) *SliceNum {
    fmt.Println("test", elem)
    fmt.Println("test", s)
    return s

func main() {
    var once sync.Once
    s := NewSlice()
    once.Do(func() {
        s.Add(16) //方法只执行一次


在执行Do方法时,方法当做参数传入,此时,Do方法内会判断其中的done 变量的值是否等于0,如果等于0即之前没有执行过此方法会继续执行Once的doSlow(f func())方法,方法内部有互斥锁,先上锁,此处再次判断o.done == 0否,如果等于即没有执行过,才进行传入的方法操作,此后在进行+1原子操作,最后解锁,如果下次再次执行此方法,由于done变量已经不等于0,所以不会在执行传入的方法



查看原文:golang sync.once解析

入群交流(和以上内容无关):Go中文网 QQ 交流群:798786647 或加微信入微信群:274768166 备注:入群;关注公众号:Go语言中文网

218 次点击  
加入收藏 微博
1 回复  |  直到 2019-08-01 11:10:08
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传