Update Atomic Counters example to use atomic.Uint64 (#490)
* Update Atomic Counters example to use atomic.Uint64 This commit updates the Atomic Counters example to follow atomic's recommendation of using atomic.Uint64 instead of uint64 (same for other types) and then calling methods on it, instead of calling atomic.AddUint64(). It also updates the comments and empty lines a bit to look better on the website. * Run tools/build again * Fix comments
This commit is contained in:
@@ -15,9 +15,9 @@ import (
|
||||
|
||||
func main() {
|
||||
|
||||
// We'll use an unsigned integer to represent our
|
||||
// We'll use an atomic integer type to represent our
|
||||
// (always-positive) counter.
|
||||
var ops uint64
|
||||
var ops atomic.Uint64
|
||||
|
||||
// A WaitGroup will help us wait for all goroutines
|
||||
// to finish their work.
|
||||
@@ -30,12 +30,11 @@ func main() {
|
||||
|
||||
go func() {
|
||||
for c := 0; c < 1000; c++ {
|
||||
// To atomically increment the counter we
|
||||
// use `AddUint64`, giving it the memory
|
||||
// address of our `ops` counter with the
|
||||
// `&` syntax.
|
||||
atomic.AddUint64(&ops, 1)
|
||||
|
||||
// To atomically increment the counter we use `Add`.
|
||||
ops.Add(1)
|
||||
}
|
||||
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
@@ -43,10 +42,8 @@ func main() {
|
||||
// Wait until all the goroutines are done.
|
||||
wg.Wait()
|
||||
|
||||
// It's safe to access `ops` now because we know
|
||||
// no other goroutine is writing to it. Reading
|
||||
// atomics safely while they are being updated is
|
||||
// also possible, using functions like
|
||||
// `atomic.LoadUint64`.
|
||||
fmt.Println("ops:", ops)
|
||||
// Reading atomics safely while they are being updated is
|
||||
// possible using functions like `Load`, although here it's
|
||||
// safe anyway, because no goroutines are writing to 'ops'.
|
||||
fmt.Println("ops:", ops.Load())
|
||||
}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
7b491b40d56a77b01d8e2bd08366de081a4e8d99
|
||||
j-14agntvEO
|
||||
806f385f4485c3e9d10fe319744dd58ab77adaaf
|
||||
LfAMxMppwL-
|
||||
|
||||
Reference in New Issue
Block a user