“select” statement chooses which of a set of possible send or receive operations will proceed. It looks similar to a “switch” statement but with the cases all referring to communication operations.
var ch1 = make(chanint) var ch2 = make(chanint) var chs = []chanint{ch1, ch2} var numbers = []int{1, 2, 3, 4, 5}
funcinit() { runtime.GOMAXPROCS(runtime.NumCPU()) } funcmain() { /* x := make(chan int, 2) y := make(chan int, 1) x <- 7 x <- 8 x <- 9 y <- 9 随机进入 select { case e := <-x: fmt.Println("x -- selected", e) case <-y: fmt.Println("y -- selected") }*/
//随机进入 select { case getChan(0) <- getNumber(2): fmt.Println("1st case is selected.") case getChan(1) <- getNumber(3): fmt.Println("2st case is selected.") default: fmt.Println("default!.") }
ch := make(chanint, 1024) gofunc(chanint) { for { val := <-ch fmt.Printf("val is: %d\n", val) } }(ch) tick := time.NewTicker(1 * time.Second) for i := 0; i < 20; i++ { select { case ch <- i: case <-tick.C: ch <- i fmt.Printf("%d:case<-tick\n", i) }