counter := new(int64) increment := func() { atomic.AddInt64(counter, 1) } // Run increment function concurrently go increment() go increment() go increment() // Wait for goroutines to finish time.Sleep(time.Millisecond * 100) fmt.Println(*counter) // Output: 3
v := new(sync/atomic.Value) v.Store("Hello, world!") newValue := "Goodbye, world!" oldValue := v.Swap(newValue) fmt.Println(oldValue) // Output: Hello, world! fmt.Println(v.Load()) // Output: Goodbye, world!In this example, we are using `Value` to store and swap values atomically. The `Store` function sets the value of `v` to "Hello, world!". The `Swap` function replaces the value of `v` with `newValue` and returns the old value, which is then printed to the console. The `Load` function is used to retrieve the current value of `v`. Overall, the `sync/atomic` package library is used in Go for low-level atomic memory operations, making it useful for concurrent programming.