Lazy Values With Sync.OnceValue And OnceFunc
Compute an expensive configuration value once with sync.OnceValue so concurrent callers share one result, and gate one-shot warnings with sync.OnceFunc.
Code
package main
import (
"fmt"
"strconv"
"strings"
"sync"
)
// OnceValue:返回的函数只在第一次调用时计算,之后并发复用同一结果
var workerLimit = sync.OnceValue(func() int {
fmt.Println("computing worker limit (printed once)")
if n, err := strconv.Atoi(strings.TrimSpace(" 64 ")); err == nil && n > 0 {
return n
}
return 4 // 解析失败时的缺省值
})
// OnceFunc:只关心「做过没有」的一次性动作
var warnLegacy = sync.OnceFunc(func() {
fmt.Println("legacy flag --insecure is deprecated")
})
func main() {
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("worker limit:", workerLimit())
warnLegacy()
}()
}
wg.Wait()
}How the operations stack up
Lazy Values With Sync.OnceValue And OnceFunc is built around the function main.
Iteration happens inside for i := 0; i < 8; i++ — everything outside it runs once. The task is handed to a goroutine and runs concurrently. The function registers its cleanup up front with defer, so no exit path forgets it.
Putting it to use
Running the file prints labeled results such as computing worker limit (printed once), legacy flag --insecure is deprecated, worker limit: — each operation’s effect is visible in the output.
Core lines
var workerLimit = sync.OnceValue(func() int {
fmt.Println("computing worker limit (printed once)")
if n, err := strconv.Atoi(strings.TrimSpace(" 64 ")); err == nil && n > 0 {
return n
}
return 4 // 解析失败时的缺省值
})
var warnLegacy = sync.OnceFunc(func() {
fmt.Println("legacy flag --insecure is deprecated")
})
func main() {
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("worker limit:", workerLimit())
warnLegacy()
}()
}
wg.Wait()
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Lazy Values With Sync.OnceValue And OnceFunc print when run?
- Running the file directly is enough — expect labeled output lines such as `computing worker limit (printed once)`, `legacy flag --insecure is deprecated`, `worker limit:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.