Created
June 12, 2013 15:29
-
-
Save droxer/5766337 to your computer and use it in GitHub Desktop.
Goroutine channel with select
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
| package main | |
| import ( | |
| "fmt" | |
| "math/rand" | |
| "time" | |
| ) | |
| func boring(msg string) <-chan string { | |
| c := make(chan string) | |
| go func() { | |
| for i := 0; ; i++ { | |
| c <- fmt.Sprintf("%s %d", msg, i) | |
| time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) | |
| } | |
| }() | |
| return c | |
| } | |
| func main() { | |
| c := boring("joe") | |
| timeout := time.After(1 * time.Second) //Timout for whole conversation. | |
| for { | |
| select { | |
| case s := <- c: | |
| fmt.Println(s) | |
| case <- timeout: | |
| fmt.Println("You talk to much") | |
| return | |
| } | |
| } | |
| fmt.Println("You are both boring; I'm leaving") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment