Sobes.tech
Junior — Middle

Selgitage sync.Once struktuuri eesmärki ja tööpõhimõtet Go keeles.

sobes.tech AI

Vastus AI-lt

sync.Once in Go is used to ensure that a specific operation (e.g., initialization) is performed only once, even if multiple goroutines call it simultaneously. This is useful for lazy initialization or resource setup.

Working principle:

  • sync.Once contains an internal flag that tracks whether the function has already been executed.
  • The method Do(f func()) accepts a function f and guarantees it will be called only once.
  • If multiple goroutines call Do at the same time, only one will execute the function, 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.