Skip to content

Instantly share code, notes, and snippets.

@droxer
Created June 12, 2013 15:29
Show Gist options
  • Select an option

  • Save droxer/5766337 to your computer and use it in GitHub Desktop.

Select an option

Save droxer/5766337 to your computer and use it in GitHub Desktop.
Goroutine channel with select
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