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, 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)]
}