Skip to content

Instantly share code, notes, and snippets.

@qianjigui
Last active August 29, 2015 14:06
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 qianjigui/7f60d0b16dbe3b7445e0 to your computer and use it in GitHub Desktop.
Save qianjigui/7f60d0b16dbe3b7445e0 to your computer and use it in GitHub Desktop.
GO concurrent demo
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