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.
11 // Once is an object that will perform exactly one action.
13 // A Once must not be copied after first use.
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).
19 // done indicates whether the action has been performed.
20 // It is first in the struct because it is used in the hot path.
21 // The hot path is inlined at every call site.
22 // Placing done first allows more compact instructions on some architectures (amd64/386),
23 // and fewer instructions (to calculate offset) on other architectures.
28 // Do calls the function f if and only if Do is being called for the
29 // first time for this instance of Once. In other words, given
33 // if once.Do(f) is called multiple times, only the first call will invoke f,
34 // even if f has a different value in each invocation. A new instance of
35 // Once is required for each function to execute.
37 // Do is intended for initialization that must be run exactly once. Since f
38 // is niladic, it may be necessary to use a function literal to capture the
39 // arguments to a function to be invoked by Do:
41 // config.once.Do(func() { config.init(filename) })
43 // Because no call to Do returns until the one call to f returns, if f causes
44 // Do to be called, it will deadlock.
46 // If f panics, Do considers it to have returned; future calls of Do return
48 func (o *Once) Do(f func()) {
49 // Note: Here is an incorrect implementation of Do:
51 // if o.done.CompareAndSwap(0, 1) {
55 // Do guarantees that when it returns, f has finished.
56 // This implementation would not implement that guarantee:
57 // given two simultaneous calls, the winner of the cas would
58 // call f, and the second would return immediately, without
59 // waiting for the first's call to f to complete.
60 // This is why the slow path falls back to a mutex, and why
61 // the o.done.Store must be delayed until after f returns.
63 if o.done.Load() == 0 {
64 // Outlined slow-path to allow inlining of the fast-path.
69 func (o *Once) doSlow(f func()) {
72 if o.done.Load() == 0 {