Last active
May 20, 2016 13:59
-
-
Save dreh23/b1ed7bbca87c233870876b862d752a43 to your computer and use it in GitHub Desktop.
Request race as described here: https://blog.golang.org/go-concurrency-patterns-timing-out-and
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" | |
"math/rand" | |
"time" | |
) | |
type Server string | |
func (s *Server) DoQuery(url string, i int) []byte { | |
rand.Seed(time.Now().UnixNano()) | |
rnd := rand.Intn(10) | |
fmt.Printf("%v is taking %v seconds to repsond\n", *s, rnd) | |
time.Sleep(time.Duration(rnd) * time.Second) | |
return []byte(*s + " wins: Here be dragons!") | |
} | |
func main() { | |
fmt.Println(string(doSomething())) | |
} | |
func doSomething() []byte { | |
var s = []Server{"server 1", "server 2", "server 3"} | |
task := "task" | |
return Query(s, task) | |
} | |
func Query(list []Server, task string) []byte { | |
var ch = make(chan []byte, 1) | |
i := 0 | |
for _, s := range list { | |
go func(c Server) { | |
select { | |
case ch <- c.DoQuery(task, i): | |
fmt.Println("Done") | |
default: | |
} | |
}(s) | |
i++ | |
} | |
defer close(ch) | |
return <-ch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment