forked from andey-robins/S22-4010
/
atomic.go
55 lines (47 loc) · 933 Bytes
/
atomic.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
)
func main() {
state := make(map[int]int)
mutex := &sync.Mutex{}
var nRead uint64
var nWrite uint64
const randRange = 15
for ii := 0; ii < 100; ii++ {
go func() {
total := 0
for {
key := rand.Intn(randRange)
mutex.Lock()
total += state[key]
mutex.Unlock()
atomic.AddUint64(&nRead, 1)
time.Sleep(time.Millisecond)
}
}()
}
for jj := 0; jj < 50; jj++ {
go func() {
for {
key := rand.Intn(randRange)
val := rand.Intn(100)
mutex.Lock()
state[key] = val
mutex.Unlock()
atomic.AddUint64(&nWrite, 1)
time.Sleep(time.Millisecond)
}
}()
}
time.Sleep(time.Second * 1)
nReadTotal := atomic.LoadUint64(&nRead)
nWriteTotal := atomic.LoadUint64(&nWrite)
mutex.Lock()
fmt.Printf("ReadOps: %d\nWriteOps: %d\nFinal State: %+v\n", nReadTotal, nWriteTotal, state)
mutex.Unlock()
}