User Tools

Site Tools


go:concurrency:once

sync.Once

What is it?

`sync.Once` ensures that a function is executed only once, even when called by multiple goroutines concurrently.

What is it used for?

  • One-time initialization (lazy init), e.g., create a singleton, load config once.
  • Safe “initialize-on-first-use” without manual locking.

When to use

  • You need exactly-once initialization across goroutines.
  • The initialization must happen at most once, not zero-or-more.

Example

package main
 
import (
    "fmt"
    "sync"
)
 
var once sync.Once
var value string
 
func initValue() {
    value = "initialized"
}
 
func GetValue() string {
    once.Do(initValue)
    return value
}
 
func main() {
    fmt.Println(GetValue())
}

Notes / pitfalls

  • If the function passed to `Do()` panics, `Once` is considered “done” (it will not run again).
  • Use `Once` for initialization only; do not use it as a general lock.

Hard words (English)

  • ensure /ɪnˈʃʊr/: đảm bảo
  • executed /ˈeksɪkjuːtɪd/: được thực thi
  • initialization /ɪˌnɪʃələˈzeɪʃən/: khởi tạo
  • singleton /ˈsɪŋɡəlˌtən/: đối tượng duy nhất (một instance)
  • lazy /ˈleɪzi/: trì hoãn (chỉ làm khi cần)
  • panic /ˈpænɪk/: lỗi runtime kiểu “panic”
go/concurrency/once.txt · Last modified: by phong2018