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

原子操作有问题 #1

Open
baozh opened this issue Mar 24, 2018 · 2 comments
Open

原子操作有问题 #1

baozh opened this issue Mar 24, 2018 · 2 comments

Comments

@baozh
Copy link

baozh commented Mar 24, 2018

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

@yangwenmai
Copy link
Owner

Thanks, I will be take a look.

@shockerli
Copy link

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

Repository owner deleted a comment from AMBzPHOTOz Mar 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants