Junior — Middle
Mis on sync.Once tüübi peamine roll Go niitide sünkroniseerimisel?
sobes.tech AI
Vastus AI-lt
The sync.Once type in Go is used to ensure that a specific piece of code is executed exactly once, even if called from multiple threads (goroutines).
Its main role is safe initialization of resources (e.g., creating a singleton), to prevent race conditions and repeated execution.
Example of usage:
var once sync.Once
var config *Config
func loadConfig() {
config = &Config{/* initialization */}
}
func GetConfig() *Config {
once.Do(loadConfig) // loadConfig will be called only once
return config
}
Thus, sync.Once guarantees thread-safe, one-time execution of a function.