sync.Once in Go
Exactly-once initialization, safe from any number of goroutines.
var (
setupOnce sync.Once
table map[string]int
)
func lookup(key string) int {
setupOnce.Do(func() {
table = map[string]int{"basics": 39, "traits": 19}
})
return table[key]
}
var expensive = sync.OnceValue(func() int {
return 40 + 2
})
func answer() int { return expensive() }
How it works
Doruns the function the first time and never again.- Later callers block until that first run finishes.
OnceValueis the newer form that returns the result.
Keywords and builtins used here
funcintmapreturnstringvar
The run, in numbers
- Lines
- 17
- Characters to type
- 283
- Tokens
- 82
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 47 seconds.
Step 3 of 5 in Synchronization, step 16 of 25 in Concurrency.