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.

GoConfig Management

Code

gosnippet
35 lines
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

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:`.