2016-08-05 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / libgo / go / sync / once.go
blobd8ef952ea5489762cdf17712b321668dfdc8da32
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 // If f panics, Do considers it to have returned; future calls of Do return
33 // without calling f.
35 func (o *Once) Do(f func()) {
36 if atomic.LoadUint32(&o.done) == 1 {
37 return
39 // Slow-path.
40 o.m.Lock()
41 defer o.m.Unlock()
42 if o.done == 0 {
43 defer atomic.StoreUint32(&o.done, 1)
44 f()