Last active
December 30, 2019 14:47
-
-
Save betandr/e77320b9a21e6f16969fbe88e0e72537 to your computer and use it in GitHub Desktop.
Make multiple queries and return the fastest in Go, using goroutines and a buffered channel
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" | |
"strings" | |
"time" | |
) | |
// multiQuery uses a buffered channel, otherwise the two slower goroutines | |
// would get stuck trying to send their responses on a channel from which | |
// no goroutine will ever receive. This bug is a _goroutine leak_. | |
func multiQuery() string { | |
responses := make(chan string, 3) | |
go func() { responses <- request("asia.example.com") }() | |
go func() { responses <- request("us.example.com") }() | |
go func() { responses <- request("europe.example.com") }() | |
return <-responses // return the quickest response | |
} | |
// spoof a very long request | |
func request(hostname string) (response string) { | |
rand.Seed(time.Now().UnixNano()) | |
time.Sleep(time.Duration(rand.Intn(100000))) | |
return strings.Split(hostname, ".")[0] | |
} | |
func main() { | |
fmt.Printf("%s returned first\n", multiQuery()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment