golang channel select
尝试多个channel同时触发时,select的表现:
package main import ( "fmt" "time" ) func loop(ch chan int){ for i := 0; i < 10; i++ { ch <- i } close(ch) } func main() { ch1 := make(chan int, 100) ch2 := make(chan int, 100) go loop(ch1) go loop(ch2) for{ select{ case j, ok := <- ch2: if false == ok { goto End } fmt.Println("ch2", j) case i,ok := <- ch1: if false == ok { goto End } fmt.Println("ch1", i) case <-time.After(5 * time.Second): fmt.Println("time's up") goto End } } End: fmt.Println("finish!") }
输出
ch1 0 ch1 1 ch1 2 ch1 3 ch1 4 ch1 5 ch1 6 ch1 7 ch1 8 ch1 9 finish!
package main import ( "fmt" "time" ) func loop(ch chan int){ for i := 0; i < 10; i++ { ch <- i } close(ch) } func main() { ch1 := make(chan int, 100) ch2 := make(chan int, 100) go loop(ch2)//把ch2的调度提到前面 go loop(ch1) for{ select{ case j, ok := <- ch2: if false == ok { goto End } fmt.Println("ch2", j) case i,ok := <- ch1: if false == ok { goto End } fmt.Println("ch1", i) case <-time.After(5 * time.Second): fmt.Println("time's up") goto End } } End: fmt.Println("finish!") }
输出:
ch2 0 ch2 1 ch2 2 ch2 3 ch2 4 ch2 5 ch2 6 ch2 7 ch2 8 ch2 9 finish!
package main import ( "fmt" "time" "runtime" ) func loop(ch chan int){ for i := 0; i < 10; i++ { runtime.Gosched()//给别的goroutine让渡出一些调度时间 ch <- i } close(ch) } func main() { ch1 := make(chan int, 100) ch2 := make(chan int, 100) go loop(ch2) go loop(ch1) for{ select{ case j, ok := <- ch2: if false == ok { goto End } fmt.Println("ch2", j) case i,ok := <- ch1: if false == ok { goto End } fmt.Println("ch1", i) case <-time.After(5 * time.Second): fmt.Println("time's up") goto End } } End: fmt.Println("finish!") }
输出:
ch2 0
ch1 0
ch2 1
ch1 1
ch2 2
ch1 2
ch2 3
ch1 3
ch2 4
ch1 4
ch2 5
ch1 5
ch2 6
ch1 6
ch2 7
ch1 7
ch2 8
ch1 8
ch2 9
finish!