Created
November 5, 2018 12:53
-
-
Save alxarch/c77ec336ec7d8e235f39c12166be51d2 to your computer and use it in GitHub Desktop.
Like sync.Once but with errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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