golang sync.once解析

實(shí)現(xiàn)原理(當(dāng)前代碼版本go version go1.11.4 )

1.atomic 原子操作計(jì)數(shù)器,用于記錄此Once對象下的done的值,func()方法只執(zhí)行一次
2.使用Mutex互斥鎖保證多協(xié)程操作的安全性

由于代碼量比較少貼出源碼如下:

// 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 (
    "sync/atomic"
)

// 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.
        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()
    }
}

golang中sync包中的sync.Once.Do(f func())用于只執(zhí)行一次的 func()方法,Mutex互斥鎖的實(shí)現(xiàn)本章不做探討

調(diào)用的例子:

package main

import (
    "fmt"
    "sync"
)

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) //方法只執(zhí)行一次
    })

}

在執(zhí)行Do方法時(shí),方法當(dāng)做參數(shù)傳入,此時(shí),Do方法內(nèi)會(huì)判斷其中的done 變量的值是否等于0,如果等于0即之前沒有執(zhí)行過此方法會(huì)繼續(xù)執(zhí)行Once的doSlow(f func())方法,方法內(nèi)部有互斥鎖,先上鎖,此處再次判斷o.done == 0否,如果等于即沒有執(zhí)行過,才進(jìn)行傳入的方法操作,此后在進(jìn)行+1原子操作,最后解鎖,如果下次再次執(zhí)行此方法,由于done變量已經(jīng)不等于0,所以不會(huì)在執(zhí)行傳入的方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容