Skip to content

Instantly share code, notes, and snippets.

@alxarch
Created November 5, 2018 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxarch/c77ec336ec7d8e235f39c12166be51d2 to your computer and use it in GitHub Desktop.
Save alxarch/c77ec336ec7d8e235f39c12166be51d2 to your computer and use it in GitHub Desktop.
Like sync.Once but with errors
// OnceNoError is like sync.Once but retries until no error occured.
type OnceNoError struct {
mu sync.Mutex
done uint32
}
func (once *OnceNoError) Do(fn func() error) (err error) {
if atomic.LoadUint32(&once.done) == 1 {
return
}
once.mu.Lock()
defer once.mu.Unlock()
if once.done == 0 {
defer func() {
if err == nil {
atomic.StoreUint32(&once.done, 1)
}
}()
err = fn()
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment