Created
July 6, 2015 21:12
-
-
Save riston/4ed6a874a18bf3c338f2 to your computer and use it in GitHub Desktop.
Go concurrency example
This file contains hidden or 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
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