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

fix issues/3: Starting from the second round, the first object will be fetched twice #4

Merged
merged 6 commits into from
Jun 5, 2024

Conversation

superbear
Copy link
Contributor

@superbear superbear commented Jun 5, 2024

Description

Starting from the second round, the first object will be fetched twice

Code

// go version: 1.18
package main

import (
	"fmt"
	"net/url"

	roundrobin "github.com/thegeekyasian/round-robin-go"
)

func main() {
	rr, _ := roundrobin.New(
		&url.URL{Host: "192.168.0.1"},
		&url.URL{Host: "192.168.0.2"},
		&url.URL{Host: "192.168.0.3"},
		&url.URL{Host: "192.168.0.4"},
	)

	for i := 0; i < 20; i++ {
		fmt.Println(rr.Next().Host)
	}
}

// output
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.1
192.168.0.1

192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.1
192.168.0.1

Why?

when the next field is greater than the length of the object, the first object will be fetched and next will be reset to 0. The next time the Next method is called, next field will be 1, 1 - 1 = 0, so the first object will be fetched.

// Next returns the next object.
func (r *RoundRobin[O]) Next() *O {
	n := atomic.AddUint32(&r.next, 1)

	if int(n) > len(r.objects) {
		atomic.StoreUint32(&r.next, 0) // reset next field
		n = 1
	}
	return r.objects[(int(n)-1)%len(r.objects)]
}

superbear and others added 4 commits June 6, 2024 00:28
…e first object will be fetched and next will be reset to 0. The next time the Next method is called, the second object should be fetched, but in fact the first object will be fetched.
fix: starting from the second round, the first object will be fetched twice && update test cases && add Building and testing Go GitHub Actions
@superbear superbear changed the title fix issues/3 fix issues/3: Starting from the second round, the first object will be fetched twice Jun 5, 2024
@thegeekyasian
Copy link
Owner

@superbear Good catch, thank you for raising the PR with the fix 🚀

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

Successfully merging this pull request may close these issues.

2 participants