Skip to content

Instantly share code, notes, and snippets.

@riston
Created July 6, 2015 21:12
Show Gist options
  • Save riston/4ed6a874a18bf3c338f2 to your computer and use it in GitHub Desktop.
Save riston/4ed6a874a18bf3c338f2 to your computer and use it in GitHub Desktop.
Go concurrency example
s := func(name string) string {
time.Sleep(4 * time.Second)
fmt.Println("Do something", name)
return "Done"
}
results := []string{}
c := make(chan string)
go func() { c <- s("first") }()
go func() { c <- s("second") }()
go func() { c <- s("third") }()
timeout := time.After(5 * time.Second)
for i := 0; i < 3; i++ {
select {
case result := <-c:
results = append(results, result)
case <-timeout:
fmt.Println("Timed out")
return
}
}
fmt.Println("Until all is done", results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment