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