Use sync/atomic.Value to safely share a single value across multiple goroutines without explicit locking.
Use sync/atomic.Value to store a value that changes infrequently but is read by many goroutines without locks. Create a sync/atomic.Value instance, store the initial value with Store, and retrieve it with Load in your goroutines.
package main
import (
"sync/atomic"
"fmt"
)
var config atomic.Value
func main() {
config.Store("initial")
go func() {
v := config.Load()
fmt.Println(v) // Prints: initial
}()
config.Store("updated")
}
Think of atomic.Value as a shared whiteboard where anyone can read the current message instantly, but only one person can write a new message at a time without stopping everyone else. It is used when you have a setting or configuration that updates rarely but needs to be checked constantly by many parts of your program. This prevents crashes or data corruption that happen when multiple threads try to read and write the same variable simultaneously.