-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path36_atomic_counters.go
More file actions
33 lines (28 loc) · 855 Bytes
/
36_atomic_counters.go
File metadata and controls
33 lines (28 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package gobyexample
import (
"fmt"
"sync/atomic"
"time"
)
// AtomicCountersDemo - demonstrates managing state of multiple
// goroutines using the sync/atomic package
func AtomicCountersDemo() {
// Use an unsigned integer to represent our (always-positive) counter.
var ops uint64
// To simulate concurrent updates, we'll start 50 goroutines that each increment
// the counter about once a millisecond.
for i := 0; i < 50; i++ {
go func() {
for {
atomic.AddUint64(&ops, 1)
time.Sleep(time.Millisecond)
}
}()
}
// Wait a second to allow some ops to accumulate.
time.Sleep(time.Second)
// In order to safely use the counter while it's been updated by other goroutines,
// we extract a copy of the current value into `opsFinal` via `atomic.LoadUint64`.
opsFinal := atomic.LoadUint64(&ops)
fmt.Println("ops:", opsFinal)
}