What is the purpose of sync.Once, and how does it guarantee a piece of code runs exactly once?
Last updated
sync.Onceensures a function runs exactly once across all goroutines viaDo(f). It is the idiomatic tool for thread-safe lazy initialization (singletons, config).It uses an atomic
doneflag as a fast path and a mutex as the slow path. Concurrent callers block until the first finishes, so all see completed initialization.If
fpanics, the Once still counts as done and never retries. Never copy a Once after first use.