Created
January 13, 2022 18:35
-
-
Save evzpav/71ff015dc5648c9590402758de2d64a0 to your computer and use it in GitHub Desktop.
Golang Round Robin - Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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