Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Hammer] Throttle has mutex guarding changes #424

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions internal/hammer/hammer.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,13 +408,16 @@ func NewThrottle(opsPerSecond int) *Throttle {
}

type Throttle struct {
opsPerSecond int
tokenChan chan bool
mu sync.Mutex
opsPerSecond int

oversupply int
}

func (t *Throttle) Increase() {
t.mu.Lock()
defer t.mu.Unlock()
tokenCount := t.opsPerSecond
delta := float64(tokenCount) * 0.1
if delta < 1 {
Expand All @@ -424,6 +427,8 @@ func (t *Throttle) Increase() {
}

func (t *Throttle) Decrease() {
t.mu.Lock()
defer t.mu.Unlock()
tokenCount := t.opsPerSecond
if tokenCount <= 1 {
return
Expand All @@ -443,20 +448,27 @@ func (t *Throttle) Run(ctx context.Context) {
case <-ctx.Done(): //context cancelled
return
case <-ticker.C:
tokenCount := t.opsPerSecond
timeout := time.After(interval)
Loop:
for i := 0; i < t.opsPerSecond; i++ {
select {
case t.tokenChan <- true:
tokenCount--
case <-timeout:
break Loop
}
}
ctx, cancel := context.WithTimeout(ctx, interval)
t.supplyTokens(ctx)
cancel()
}
}
}

func (t *Throttle) supplyTokens(ctx context.Context) {
t.mu.Lock()
mhutchinson marked this conversation as resolved.
Show resolved Hide resolved
defer t.mu.Unlock()
tokenCount := t.opsPerSecond
for i := 0; i < t.opsPerSecond; i++ {
select {
case t.tokenChan <- true:
tokenCount--
case <-ctx.Done():
t.oversupply = tokenCount
return
}
}
t.oversupply = 0
}

func (t *Throttle) String() string {
Expand Down
Loading