Last active
June 4, 2020 09:02
-
-
Save olehcambel/a179346a84d0929569dc79c7cd64c443 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
) | |
// 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) | |
} |
This file contains hidden or 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" | |
) | |
// 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) | |
} |
This file contains hidden or 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
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