Source file src/pkg/sync/once.go
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
5 package sync
6
7 import (
8 "sync/atomic"
9 )
10
11 // Once is an object that will perform exactly one action.
12 type Once struct {
13 m Mutex
14 done uint32
15 }
16
17 // Do calls the function f if and only if the method is being called for the
18 // first time with this receiver. In other words, given
19 // var once Once
20 // if once.Do(f) is called multiple times, only the first call will invoke f,
21 // even if f has a different value in each invocation. A new instance of
22 // Once is required for each function to execute.
23 //
24 // Do is intended for initialization that must be run exactly once. Since f
25 // is niladic, it may be necessary to use a function literal to capture the
26 // arguments to a function to be invoked by Do:
27 // config.once.Do(func() { config.init(filename) })
28 //
29 // Because no call to Do returns until the one call to f returns, if f causes
30 // Do to be called, it will deadlock.
31 //
32 func (o *Once) Do(f func()) {
33 if atomic.LoadUint32(&o.done) == 1 {
34 return
35 }
36 // Slow-path.
37 o.m.Lock()
38 defer o.m.Unlock()
39 if o.done == 0 {
40 f()
41 atomic.CompareAndSwapUint32(&o.done, 0, 1)
42 }
43 }