Skip to content

Commit 8ff61b2

Browse files
committed
show correct counts immediately after Stop
1 parent 697c5dd commit 8ff61b2

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

limiter_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,23 @@ func TestLimiter_double_Wrap(t *testing.T) {
4242
t.Error(d1, d2)
4343
}
4444
}
45+
46+
func TestLimiter_Stop_flushesCount(t *testing.T) {
47+
l := NewLimiter(0)
48+
49+
r := bytes.NewReader(make([]byte, 10))
50+
buf := make([]byte, 10)
51+
n, err := l.Reads.io(r.Read, buf)
52+
if err != nil {
53+
t.Fatal(err)
54+
}
55+
if n != 10 {
56+
t.Fatal(n)
57+
}
58+
59+
l.Stop()
60+
61+
if got := l.Reads.Count.Load(); got != int64(n) {
62+
t.Fatalf("got %d want %d", got, n)
63+
}
64+
}

operation.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type Operation struct {
1919
avail atomic.Int64
2020
count atomic.Int64
2121
ch <-chan int64
22+
doneCh chan struct{}
2223
reader bool
2324
mu sync.Mutex // protects following
2425
stopCh chan struct{}
@@ -30,6 +31,7 @@ func NewOperation(t *Ticker, limits []int64, idx int) (op *Operation) {
3031
Ticker: t,
3132
ch: ch,
3233
stopCh: make(chan struct{}),
34+
doneCh: make(chan struct{}),
3335
reader: idx == 0,
3436
}
3537
var limit int64
@@ -52,10 +54,15 @@ func (op *Operation) Stop() {
5254
if ch != nil {
5355
close(ch)
5456
}
57+
<-op.doneCh
5558
}
5659

5760
func (op *Operation) run(ch chan<- int64) {
58-
defer close(ch)
61+
defer func() {
62+
close(ch)
63+
op.Count.Add(op.count.Swap(0))
64+
close(op.doneCh)
65+
}()
5966

6067
op.mu.Lock()
6168
stopCh := op.stopCh

0 commit comments

Comments
 (0)