【go 原始碼】sync.Once 詳解

xmgee發表於2019-10-31

# sync.Once 原始碼閱讀

## 1.Demo

```
package main

import (
"fmt"
"sync"
"time"
)

func main() {
var once sync.Once

for i:=0;i<=10;i++{
go once.Do(func() {
fmt.Println("hello world")
})
}

time.Sleep(time.Second * 2)
}
```

## 2.介紹

sync.Once是sync包中的一個物件,它只有一個方法Do,這個方法很特殊,在程式執行過程中,無論被多少次呼叫,只會執行一次,就與結構體的名稱一樣,once(一次)。那它是如何做的呢?

## 3.使用場景

當程式執行過程中,在會被多次呼叫的地方卻只想執行一次某程式碼塊。就可以全域性宣告一個once,然後用once.Do()來之行此程式碼塊。

## 4.原始碼

```
// 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 {
m Mutex
done uint32
}

// 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()) {
if atomic.LoadUint32(&o.done) == 1 {
return
}
// Slow-path.
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}

```

## 5.原始碼解析

可以看到once結構體中,有兩個欄位,m是了保證併發安全性的,done是標誌是否已經執行過此方法,如果done是1則表示執行過,0表示未執行。

Do方法中,首先通過atomic.LoadUint32(&o.done),來取得done的值,看是否為1,如果為1就表示已經執行過了,直接返回,未執行則繼續執行。

程式碼很簡單,就不囉嗦了,值得注意的是 `defer atomic.StoreUint32(&o.done, 1)`很精髓,為了防止f()方法中panic,無法為done賦值,作者特地使用defer。值得學習。

----

專案地址:github.com/xmge,更多go原始碼閱讀文章將在公眾號釋出:

![img](https://gosc.oss-cn-beijing.aliyuncs.com/gosc.jpg)

相關文章