1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package sync 6 7import ( 8 "sync/atomic" 9) 10 11// Once is an object that will perform exactly one action. 12// 13// A Once must not be copied after first use. 14// 15// In the terminology of [the Go memory model], 16// the return from f “synchronizes before” 17// the return from any call of once.Do(f). 18// 19// [the Go memory model]: https://go.dev/ref/mem 20type Once struct { 21 // done indicates whether the action has been performed. 22 // It is first in the struct because it is used in the hot path. 23 // The hot path is inlined at every call site. 24 // Placing done first allows more compact instructions on some architectures (amd64/386), 25 // and fewer instructions (to calculate offset) on other architectures. 26 done atomic.Uint32 27 m Mutex 28} 29 30// Do calls the function f if and only if Do is being called for the 31// first time for this instance of [Once]. In other words, given 32// 33// var once Once 34// 35// if once.Do(f) is called multiple times, only the first call will invoke f, 36// even if f has a different value in each invocation. A new instance of 37// Once is required for each function to execute. 38// 39// Do is intended for initialization that must be run exactly once. Since f 40// is niladic, it may be necessary to use a function literal to capture the 41// arguments to a function to be invoked by Do: 42// 43// config.once.Do(func() { config.init(filename) }) 44// 45// Because no call to Do returns until the one call to f returns, if f causes 46// Do to be called, it will deadlock. 47// 48// If f panics, Do considers it to have returned; future calls of Do return 49// without calling f. 50func (o *Once) Do(f func()) { 51 // Note: Here is an incorrect implementation of Do: 52 // 53 // if o.done.CompareAndSwap(0, 1) { 54 // f() 55 // } 56 // 57 // Do guarantees that when it returns, f has finished. 58 // This implementation would not implement that guarantee: 59 // given two simultaneous calls, the winner of the cas would 60 // call f, and the second would return immediately, without 61 // waiting for the first's call to f to complete. 62 // This is why the slow path falls back to a mutex, and why 63 // the o.done.Store must be delayed until after f returns. 64 65 if o.done.Load() == 0 { 66 // Outlined slow-path to allow inlining of the fast-path. 67 o.doSlow(f) 68 } 69} 70 71func (o *Once) doSlow(f func()) { 72 o.m.Lock() 73 defer o.m.Unlock() 74 if o.done.Load() == 0 { 75 defer o.done.Store(1) 76 f() 77 } 78} 79