Skip to content

Instantly share code, notes, and snippets.

@evzpav
Created January 13, 2022 18:35
Show Gist options
  • Save evzpav/71ff015dc5648c9590402758de2d64a0 to your computer and use it in GitHub Desktop.
Save evzpav/71ff015dc5648c9590402758de2d64a0 to your computer and use it in GitHub Desktop.
Golang Round Robin - Algorithm
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
concurrentCalls := 20
r := NewRobin("1", "2", "3", "4", "5")
urlCalledChan := make(chan string)
var wg sync.WaitGroup
for i := 0; i < concurrentCalls; i++ {
wg.Add(1)
go func() {
nextUrl := r.Next()
urlCalledChan <- nextUrl
wg.Done()
}()
}
go func() {
for url := range urlCalledChan {
fmt.Println(url)
}
}()
wg.Wait()
}
type robin struct {
next int64
urls []string
}
func NewRobin(urls ...string) *robin {
return &robin{
urls: urls,
}
}
func (r *robin) Next() string {
next := atomic.AddInt64(&r.next, int64(1))
return r.urls[(int(next)-1)%len(r.urls)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment