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

Update NextIndex function. #11

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
11 changes: 9 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,14 @@ func (s *ServerPool) AddBackend(backend *Backend) {

// NextIndex atomically increase the counter and return an index
func (s *ServerPool) NextIndex() int {
return int(atomic.AddUint64(&s.current, uint64(1)) % uint64(len(s.backends)))
for {
current := atomic.LoadUint64(&s.current)
// increase the counter in a circular fashion
next := (current + 1) % uint64(len(s.backends))
if atomic.CompareAndSwapUint64(&s.current, current, next) {
return int(next)
}
}
}

// MarkBackendStatus changes a status of a backend
Expand All @@ -75,7 +82,7 @@ func (s *ServerPool) GetNextPeer() *Backend {
next := s.NextIndex()
l := len(s.backends) + next // start from next and move a full cycle
for i := next; i < l; i++ {
idx := i % len(s.backends) // take an index by modding
idx := i % len(s.backends) // take an index by modding
if s.backends[idx].IsAlive() { // if we have an alive backend, use it and store if its not the original one
if i != next {
atomic.StoreUint64(&s.current, uint64(idx))
Expand Down