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

add thread-safe tockenbucket touch() function #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
27 changes: 17 additions & 10 deletions tokenbucket/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tokenbucket

import (
"math/rand"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -43,19 +44,25 @@ func New(num int, rate float64, depth uint64) *Filter {

func (b *Filter) touch(it *item) bool {
now := uint64(time.Now().UnixNano())
delta := now - it.prev
it.credit += delta
it.prev = now
oldPrev := atomic.LoadUint64(&it.prev)
oldCredit := atomic.LoadUint64(&it.credit)

if it.credit > b.creditMax {
it.credit = b.creditMax
}
delta := now - oldPrev
defer atomic.StoreUint64(&it.prev, now)

newCredit := oldCredit + delta
allow := false

if it.credit > b.touchCost {
it.credit -= b.touchCost
return true
if newCredit > b.creditMax {
newCredit = b.creditMax
}
return false
if newCredit > b.touchCost {
newCredit -= b.touchCost
allow = true
}
atomic.StoreUint64(&it.credit, newCredit)

return allow
}

// Touch finds the token bucket for d, takes a token out of it and reports if
Expand Down