capypad
0 day streak
go / expert
Snippet

Lock-Free Configuration Updates with atomic.Value

atomic.Value provides an efficient way to atomically load and store values of any type. This is particularly useful for configuration objects that are read frequently by many goroutines but updated infrequently. It avoids the overhead of a RWMutex for every read operation, relying instead on low-level atomic CPU instructions.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
type Config struct { Enabled bool; Timeout time.Duration }
var globalConfig atomic.Value
 
func updateConfig(c *Config) {
globalConfig.Store(c)
}
 
func getConfig() *Config {
return globalConfig.Load().(*Config)
}
Breakdown
1
globalConfig.Store(c)
Atomically replaces the current configuration with a new pointer.
2
globalConfig.Load().(*Config)
Atomically retrieves the pointer and performs a type assertion.