Get rid of wait groups

This commit is contained in:
Julian Ospald 2017-10-07 16:42:20 +02:00
parent 9476a00648
commit ff55e2f055
No known key found for this signature in database
GPG Key ID: 511B62C09D50CD28

View File

@ -10,7 +10,6 @@ import (
"net/http"
"net/url"
"numbers/sort"
"sync"
"time"
)
@ -64,13 +63,10 @@ func numbersHandler(w http.ResponseWriter, r *http.Request) {
// Non-blocking channel for sorted results
sortChan := make(chan []int, len(rurl))
var wg sync.WaitGroup
// fetch all URLs asynchronously and sort them
for i := range rurl {
wg.Add(1)
go func(url string) {
defer wg.Done()
n, e := getNumbers(url, ctx)
if e == nil { // we have a usable JSON list of numbers
@ -89,30 +85,29 @@ func numbersHandler(w http.ResponseWriter, r *http.Request) {
}
}(rurl[i])
}
// master routine closing the inputChan
go func() {
wg.Wait()
close(sortChan)
}()
// result list that is returned on short-circuit
var resultList []int = []int{}
// counter of how many merge operations have been performed
mc := 0
// get all sorted lists concurrently and merge them as we go
done := false
for done != true {
Outer:
for {
select {
case <-ctx.Done():
log.Printf("Waiting for URL took too long, finishing response anyway")
finishResponse(w, resultList)
return
case res, more := <-sortChan:
if more {
case res := <-sortChan:
merged := sort.MergeLists(resultList, res)
resultList = merged
} else {
log.Printf("Nothing else to sort")
done = true
mc += 1
// if we have len(rurl) merge operations, then
// all lists have been processed already
if mc >= len(rurl) {
break Outer
}
}
}