Golang sync.Once 简介与用法

1.简介

sync.Once 表示只执行函数一次。要做到这点,需要两点来保障:
(1)计数器,统计函数执行次数;
(2)线程安全,保障在多 Go 程的情况下,函数仍然只执行一次,比如锁。

import (
   "sync/atomic"
)

// Once is an object that will perform exactly one action.
type Once struct {
   m    Mutex
   done uint32
}

Once 结构体证明了之前的猜想,果然有两个变量。

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

你可能感兴趣的:(Go,基础)