Introduction
This challenge focuses on managing state in Go using the sync/atomic
package for atomic counters accessed by multiple goroutines.
This tutorial is from open-source community. Access the source code
This challenge focuses on managing state in Go using the sync/atomic
package for atomic counters accessed by multiple goroutines.
The problem is to increment a counter exactly 1000 times using 50 goroutines and the sync/atomic
package.
sync/atomic
package to increment the counter.## We expect to get exactly 50,000 operations. Had we
## used the non-atomic `ops++` to increment the counter,
## we'd likely get a different number, changing between
## runs, because the goroutines would interfere with
## each other. Moreover, we'd get data race failures
## when running with the `-race` flag.
$ go run atomic-counters.go
ops: 50000
## Next we'll look at mutexes, another tool for managing
## state.
In this challenge, we learned how to use the sync/atomic
package to manage state in Go by incrementing a counter using multiple goroutines. The AddUint64
function was used to atomically increment the counter, and a WaitGroup was used to wait for all goroutines to finish their work.