Last active
February 7, 2016 20:59
-
-
Save alexchowle/ebf62a5c6bb9bbb3f0f5 to your computer and use it in GitHub Desktop.
Golang concurrency - waiting for all to return
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 | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
ch := make(chan struct{}) | |
for i := 0; i < 3; i++ { | |
go slowRunning(ch) | |
} | |
for i := 0; i < 3; i++ { | |
<-ch | |
fmt.Println("Received...") | |
} | |
fmt.Println("Finishing.") | |
} | |
func slowRunning(ch chan<- struct{}) { | |
sleepLen := rand.Intn(5) | |
fmt.Printf("Sleeping for %d seconds.\n", sleepLen) | |
time.Sleep(time.Duration(sleepLen) * time.Second) | |
fmt.Println("Waking up...") | |
ch <- struct{}{} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment