once.go 1.7 KB

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