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

Pick方法锁调整建议 #1077

Open
tclxzx19981 opened this issue Mar 9, 2023 · 2 comments
Open

Pick方法锁调整建议 #1077

tclxzx19981 opened this issue Mar 9, 2023 · 2 comments
Assignees
Labels
bug Something isn't working

Comments

@tclxzx19981
Copy link

/core/loadbalancer/randam.go下的Pick方法锁如下调整是不是更好:
func (r *RandomStrategy) Pick() (*registry.MicroServiceInstance, error) {
r.mtx.Lock()
defer r.mtx.Unlock()

if len(r.instances) == 0 {
	return nil, ErrNoneAvailableInstance
}

k := rand.Int() % len(r.instances)
return r.instances[k], nil

}

@tclxzx19981 tclxzx19981 added the bug Something isn't working label Mar 9, 2023
@tianxiaoliang
Copy link
Member

感谢建议,请问目前的问题是什么

@tclxzx19981
Copy link
Author

目前没有遇到问题,只是看到这段代码觉得并发情况下这样锁不安全,可能会遇到除0:

   if len(r.instances) == 0 {
	return nil, ErrNoneAvailableInstance
}

r.mtx.Lock()
k := rand.Int() % len(r.instances)
r.mtx.Unlock()
return r.instances[k], nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants