1 /* 2 Copyright 2014 The Camlistore Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package internal 18 19 import ( 20 "sync" 21 "sync/atomic" 22 ) 23 24 // A Once will perform a successful action exactly once. 25 // 26 // Unlike a sync.Once, this Once's func returns an error 27 // and is re-armed on failure. 28 type Once struct { 29 m sync.Mutex 30 done uint32 31 } 32 33 // Do calls the function f if and only if Do has not been invoked 34 // without error for this instance of Once. In other words, given 35 // var once Once 36 // if once.Do(f) is called multiple times, only the first call will 37 // invoke f, even if f has a different value in each invocation unless 38 // f returns an error. A new instance of Once is required for each 39 // function to execute. 40 // 41 // Do is intended for initialization that must be run exactly once. Since f 42 // is niladic, it may be necessary to use a function literal to capture the 43 // arguments to a function to be invoked by Do: 44 // err := config.once.Do(func() error { return config.init(filename) }) 45 func (o *Once) Do(f func() error) error { 46 if atomic.LoadUint32(&o.done) == 1 { 47 return nil 48 } 49 // Slow-path. 50 o.m.Lock() 51 defer o.m.Unlock() 52 var err error 53 if o.done == 0 { 54 err = f() 55 if err == nil { 56 atomic.StoreUint32(&o.done, 1) 57 } 58 } 59 return err 60 } 61