Last active
August 29, 2015 14:06
-
-
Save qianjigui/7f60d0b16dbe3b7445e0 to your computer and use it in GitHub Desktop.
GO concurrent demo
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 main | |
// similar to Matt Aimonetti's example, read his blog! | |
// http://matt.aimonetti.net/posts/2012/11/27/real-life-concurrency-in-go/ | |
func concurrently(integers []int) []int { | |
// make a channel to talk to the goroutines | |
ch := make(chan int) | |
// prepare a slice with all the results | |
responses := []int{} | |
// iterate through all the input and send | |
// them each to their own goroutine for calc | |
for _, i := range integers { | |
go func(i int) { | |
ch <- i * i | |
}(i) | |
} | |
// loop forever until return is reached | |
for { | |
// pull a result off from the channel | |
r := <-ch | |
// add it to responses (duh), end | |
// the loop if we're done | |
responses = append(responses, r) | |
if len(responses) == len(integers) { | |
return responses | |
} | |
} | |
} | |
func main() { | |
concurrently([]int{1, 2, 3, 4, 5, 6, 7, 8}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment