Skip to content

Instantly share code, notes, and snippets.

@betandr
Last active December 30, 2019 14:47
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 betandr/e77320b9a21e6f16969fbe88e0e72537 to your computer and use it in GitHub Desktop.
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
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