Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example of using goroutines to run code concurrently
package search
import (
"fmt"
"time"
)
// Search performs a search
func Search(term string) string {
c := make(chan []string)
go func() {
c <- searchA()
}()
go func() {
c <- searchB()
}()
go func() {
c <- searchC()
}()
resultCount := 0
for i := resultCount; i < 3; i++ {
res := <-c
resultCount = resultCount + len(res)
}
/*
resultCount := 0
rA := searchA()
rB := searchB()
rC := searchC()
resultCount = len(rA) + len(rB) + len(rC)
*/
return fmt.Sprintf("Total results: %v", resultCount)
}
func searchA() []string {
// call to external API
time.Sleep(time.Duration(3000 * time.Millisecond))
result := make([]string, 1)
return result
}
func searchB() []string {
// call to external API
time.Sleep(time.Duration(3000 * time.Millisecond))
result := make([]string, 1)
return result
}
func searchC() []string {
// call to external API
time.Sleep(time.Duration(3000 * time.Millisecond))
result := make([]string, 1)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment