2014-04-11 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / libgo / go / sync / once.go
blob161ae3b3e968530524c4c519382e297a684c7426
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.
5 package sync
7 import (
8 "sync/atomic"
11 // Once is an object that will perform exactly one action.
12 type Once struct {
13 m Mutex
14 done uint32
17 // Do calls the function f if and only if Do is being called for the
18 // first time for this instance of Once. 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.
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) })
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.
32 func (o *Once) Do(f func()) {
33 if atomic.LoadUint32(&o.done) == 1 {
34 return
36 // Slow-path.
37 o.m.Lock()
38 defer o.m.Unlock()
39 if o.done == 0 {
40 f()
41 atomic.StoreUint32(&o.done, 1)