Skip to content

Instantly share code, notes, and snippets.

@rockybean
Last active October 6, 2015 13:47
Show Gist options
  • Save rockybean/afcac580ceedd38248db to your computer and use it in GitHub Desktop.
Save rockybean/afcac580ceedd38248db to your computer and use it in GitHub Desktop.
Buffered channel in golang
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
chArr := make(chan int64, 10)
for i := 0; i < 10; i++ {
go func(ch chan int64) {
randInt := rand.Intn(3)
start := time.Now().Unix()
time.Sleep(time.Duration(randInt) * time.Second)
fmt.Printf("sleep %d ,start %d,after sleep %d\n", randInt, start, time.Now().Unix())
ch <- time.Now().Unix()
}(chArr)
}
timeout := time.After(5 * time.Second)
for {
select {
case timeArr := <-chArr:
fmt.Printf("ch val is %d\n", timeArr)
case <-timeout:
fmt.Print("timeout\n")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment