Skip to content

Commit 929eaae

Browse files
committed
Fix data race #8
1 parent 0ccc1bd commit 929eaae

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

score/score.go

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type Score struct {
1616
DefaultScoreMagnification int64
1717

1818
mu sync.RWMutex
19+
cmu sync.RWMutex
1920
total sumTable
2021
count int32
2122
queue chan ScoreTag
@@ -27,6 +28,7 @@ func NewScore(ctx context.Context) *Score {
2728
Table: make(ScoreTable),
2829
DefaultScoreMagnification: 0,
2930
mu: sync.RWMutex{},
31+
cmu: sync.RWMutex{},
3032
total: make(sumTable),
3133
count: 0,
3234
queue: make(chan ScoreTag),
@@ -71,15 +73,19 @@ func (s *Score) Add(tag ScoreTag) {
7173
defer func() { recover() }()
7274

7375
if atomic.CompareAndSwapUint32(&s.closed, 0, 0) {
76+
s.cmu.RLock()
7477
s.queue <- tag
78+
s.cmu.RUnlock()
7579
atomic.AddInt32(&s.count, 1)
7680
}
7781
}
7882

7983
func (s *Score) Close() {
8084
if atomic.CompareAndSwapUint32(&s.closed, 0, 1) {
8185
atomic.AddInt32(&s.count, 1)
86+
s.cmu.Lock()
8287
close(s.queue)
88+
s.cmu.Unlock()
8389
}
8490
}
8591

0 commit comments

Comments
 (0)