Created
February 26, 2016 21:09
-
-
Save caike/97ac66c782255ed97371 to your computer and use it in GitHub Desktop.
Example of using goroutines to run code concurrently
This file contains 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 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