45. Go - Atomic Write/Load Int64
Atomic lets write and load int64 without race conditions. Alternative to Mutex or if want to just increment ints.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var counter int64
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
atomic.AddInt64(&counter, 1)
wg.Done()
}()
//fmt.Println(counter)
fmt.Println(atomic.LoadInt64(&counter))
}
wg.Wait()
fmt.Println(counter)
}
// atomic.AddInt64(ADDRESS,INCREMENT)
increments/write to a variable safely
// atomic.LoadInt64(ADDRESS)
loads/reads a variable
Comments
Post a Comment