Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjsmith/9833592 to your computer and use it in GitHub Desktop.
Save nwjsmith/9833592 to your computer and use it in GitHub Desktop.
An exercise to the viewer
package main
import (
"fmt"
"math/rand"
"time"
)
type Conn struct {
num int
}
type Result struct {
msg string
}
func (c Conn) DoQuery(query string) Result {
time.Sleep(time.Duration(rand.Intn(10)) * time.Second)
return Result{fmt.Sprintf("Conn #%d was first!", c.num)}
}
func Query(conns []Conn, query string) Result {
ch := make(chan Result, len(conns)) // buffered
for _, conn := range conns {
go func(c Conn) {
ch <- c.DoQuery(query)
}(conn)
}
return <-ch
}
func main() {
rand.Seed(int64(time.Now().UTC().Nanosecond()))
conns := make([]Conn, 10)
for i, _ := range conns {
conns[i].num = i
}
fmt.Println(Query(conns, "foo bar"))
}
package main
import (
"fmt"
"math/rand"
"time"
)
type Conn struct {
num int
}
type Result struct {
msg string
}
func (c Conn) DoQuery(query string, cancel chan bool) Result {
select {
case <-time.After(time.Duration(rand.Intn(10)) * time.Second):
return Result{fmt.Sprintf("Conn #%d was first!", c.num)}
case <-cancel:
return Result{fmt.Sprintf("Conn #%d was cancelled!", c.num)}
}
}
func Query(conns []Conn, query string) Result {
ch := make(chan Result) // buffered
cancel := make(chan bool, len(conns) - 1)
for _, conn := range conns {
go func(c Conn) {
ch <- c.DoQuery(query, cancel)
}(conn)
}
winner := <-ch
for i := 0; i < len(conns) - 1; i++ {
cancel <- true
fmt.Println((<-ch).msg)
}
return winner
}
func main() {
rand.Seed(int64(time.Now().UTC().Nanosecond()))
conns := make([]Conn, 10)
for i, _ := range conns {
conns[i].num = i
}
fmt.Println(Query(conns, "foo bar"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment