yangwenmai / ratelimit

基于令牌桶算法和漏桶算法来实现的限速限流,Golang实现。

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

原子操作有问题

baozh opened this issue · comments

func (rl *RateLimiter) Limit() bool {
        ....
	if max := atomic.LoadUint64(&rl.max); current > max {
		atomic.AddUint64(&rl.allowance, max-current) 
		....
	}
        ....

	// 没有超过限额
	atomic.AddUint64(&rl.allowance, -rl.unit)
	return false
}

如上的代码中atomic.AddUint64中传入的数必须是uint64,在注释上说明了减法用类似AddUint64(&x, ^uint64(c-1))的形式。

// AddUint64 atomically adds delta to *addr and returns the new value.
// To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)).
// In particular, to decrement x, do AddUint64(&x, ^uint64(0)).
func AddUint64(addr *uint64, delta uint64) (new uint64)

正确的写法也可参考:go.uber.org/atomic

Thanks, I will be take a look.

commented

我没看错的话,是“借鉴”了
https://github.com/bsm/ratelimit/blob/master/ratelimit.go