Atomic
- Low level atomic operations on memory.
- Lockless operation.
- Used for atomic operations on counters.
atomic.AddUint64(&ops,1)
value := atomic.LoadUint64(&ops)
Exercises
https://go.dev/play/p/s7kcfghrbof
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
func main() {
runtime.GOMAXPROCS(4)
var counter uint64
var wg sync.WaitGroup
// TODO: implement concurrency safe counter
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for c := 0; c < 1000; c++ {
// counter++
atomic.AddUint64(&counter, 1)
}
}()
}
wg.Wait()
fmt.Println("counter: ", counter)
}