Skip to content

Commit b7625c4

Browse files
committed
Fix a problem caused by data race
1 parent 7e74b98 commit b7625c4

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/rate/rate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ type Limits struct {
2121
// Wait ensures there are enough resources (n) available, blocking if necessary.
2222
func (l *Limits) Wait(n uint64) {
2323
doa.Doa(n < math.MaxUint64/2)
24-
doa.Doa(l.size <= l.capacity)
2524
l.mu.Lock()
2625
defer l.mu.Unlock()
2726
cycles := uint64(time.Since(l.last) / l.step)
@@ -39,6 +38,7 @@ func (l *Limits) Wait(n uint64) {
3938
l.size = l.size + l.addition*cycles
4039
}
4140
l.size -= n
41+
doa.Doa(l.size <= l.capacity)
4242
}
4343

4444
// NewLimits creates a new rate limiter with rate r over period p.

lib/rate/rate_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package rate
2+
3+
import (
4+
"math/rand/v2"
5+
"testing"
6+
"time"
7+
)
8+
9+
func TestMain(t *testing.T) {
10+
rate := NewLimits(128, time.Millisecond)
11+
for range 1024 {
12+
maxn := rate.capacity * 4
13+
rate.Wait(rand.Uint64() % maxn)
14+
}
15+
}

0 commit comments

Comments
 (0)