Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Last active June 4, 2020 09:02
Show Gist options
  • Save olehcambel/a179346a84d0929569dc79c7cd64c443 to your computer and use it in GitHub Desktop.
Save olehcambel/a179346a84d0929569dc79c7cd64c443 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
)
// Query a replicated database
// Teardown of late finishers is left as an exercise.
// Conn comment
type Conn int
// DoQuery comment
func (c Conn) DoQuery(q string) Result {
r := Result(q)
time.Sleep(time.Duration(rand.Int()) * time.Second)
return r
}
// Result comment
type Result string
// Query comment
func Query(conns []Conn, query string) Result {
ch := make(chan Result, 1) // buffered
for _, conn := range conns {
go func(c Conn) {
select {
case ch <- c.DoQuery(query):
default:
}
}(conn)
}
return <-ch
}
func main() {
conns := []Conn{1, 2, 3}
r := Query(conns, "SELECT * FROM users")
fmt.Println(r)
time.Sleep(5 * time.Second)
}
package main
import (
"fmt"
"math/rand"
"time"
)
// Query a replicated database
// Teardown of late finishers is left as an exercise.
// Conn comment
type Conn int
// DoQuery comment
func (c Conn) DoQuery(q string) Result {
r := Result(q)
time.Sleep(time.Duration(rand.Int()) * time.Second)
return r
}
// Result comment
type Result string
// Query comment
func Query(conns []Conn, query string) Result {
ch := make(chan Result)
done := make(chan struct{})
defer close(done)
for _, conn := range conns {
go func(c Conn) {
select {
case ch <- c.DoQuery(query):
case <-done:
}
}(conn)
}
return <-ch
}
func main() {
conns := []Conn{1, 2, 3}
r := Query(conns, "SELECT * FROM users")
fmt.Println(r)
time.Sleep(5 * time.Second)
}
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment