How to Use atomic.Value in Go

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")
}