Atomic Counters
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
// Creating an atomic.Uint64 variable named 'ops'
var ops atomic.Uint64
// Creating a WaitGroup to wait for all goroutines to finish
var wg sync.WaitGroup
// Launching 50 goroutines
for i := 0; i < 50; i++ {
// Incrementing the WaitGroup counter for each goroutine
wg.Add(1)
// Launching a goroutine
go func() {
// Performing 1000 atomic increments on the 'ops' variable
for c := 0; c < 1000; c++ {
ops.Add(1)
}
// Decrementing the WaitGroup counter when the goroutine completes
wg.Done()
}()
}
// Waiting for all goroutines to finish
wg.Wait()
// Loading the final value of 'ops' using ops.Load()
fmt.Println("ops:", ops.Load())
}Further Explanation
Last updated