Last active
August 29, 2015 13:57
-
-
Save nwjsmith/9833592 to your computer and use it in GitHub Desktop.
An exercise to the viewer
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 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")) | |
} |
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 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