Skip to content

Instantly share code, notes, and snippets.

@caike
Created February 26, 2016 21:09
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 caike/97ac66c782255ed97371 to your computer and use it in GitHub Desktop.
Save caike/97ac66c782255ed97371 to your computer and use it in GitHub Desktop.
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