Go Concurrency Part 2
Parallel Search
Let's write a program that will make multiple Google searches in parallel and return all the results once all of the responses have come back.
type search func(query string) string
func getSearch(kind string) search {
return func(query string) string {
// Optional: implement actual HTTP requests.
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
return fmt.Sprintf("%s result for %q\n", kind, query)
}
}
var (
web = getSearch("web")
image = getSearch("image")
video = getSearch("video")
)Now we can write our google function.
func google(query string) (results []string) {
ch := make(chan string)
go func() {
ch <- web(query)
}()
go func() {
ch <- image(query)
}()
go func() {
ch <- video(query)
}()
for i := 0; i < 3; i++ {
r := <-ch
results = append(results, r)
}
return results
}We run it in main.
We should expect to see the following output.
Search with Timeout
We can make our search a bit more robust by introducing timeout because there's a chance that some results won't come back for a while and we don't want to wait for it.
Distributed Search
Suppose we can make requests to make multiple slave/replica servers and only return searches that complete in under 80 milliseconds.
Now we can make requests to multiple slave servers.
Last updated