-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscoreboard_rw.go
56 lines (50 loc) · 1.04 KB
/
scoreboard_rw.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
56
package main
import (
"fmt"
"sync"
)
type MutexScoreboardManager struct {
l sync.RWMutex
scoreboard map[string]int
}
func NewMutexScoreboardManager() *MutexScoreboardManager {
return &MutexScoreboardManager{
scoreboard: map[string]int{},
}
}
func (msm *MutexScoreboardManager) Update(name string, val int) {
msm.l.Lock()
defer msm.l.Unlock()
msm.scoreboard[name] = val
}
func (msm *MutexScoreboardManager) Read(name string) (int, bool) {
msm.l.RLock()
defer msm.l.RUnlock()
val, ok := msm.scoreboard[name]
return val, ok
}
func ScoreBoardRW() {
msm := NewMutexScoreboardManager()
teams := []string{"Lions", "Tigers", "Bears"}
var wg sync.WaitGroup
wg.Add(len(teams))
for _, v := range teams {
go func(team string) {
defer wg.Done()
for i := 0; i < 10; i++ {
curScore, found := msm.Read(team)
if !found {
curScore = 10
} else {
curScore += len(team)
}
msm.Update(team, curScore)
}
}(v)
}
wg.Wait()
for _, v := range teams {
score, found := msm.Read(v)
fmt.Println(v, score, found)
}
}