Junior — Middle
Explain the purpose and how the sync.Once structure works in Go.
sobes.tech AI
Answer from AI
sync.Once in Go is used to ensure that a specific operation (for example, initialization) is performed exactly once, even if multiple goroutines call it simultaneously. This is useful for lazy initialization or resource setup.
How it works:
sync.Oncecontains an internal flag that tracks whether the function has already been executed.- The
Do(f func())method takes a functionfand guarantees that it will be called only once. - If multiple goroutines call
Doat the same time, only one will execute the function, while others will wait for it to complete.
Example:
var once sync.Once
func initialize() {
fmt.Println("Initialization complete")
}
func main() {
for i := 0; i < 5; i++ {
go func() {
once.Do(initialize)
}()
}
time.Sleep(time.Second) // Wait for goroutines to finish
}
In this example, the message "Initialization complete" will be printed exactly once.