首页 > 代码库 > golang channel select

golang channel select

尝试多个channel同时触发时,select的表现:

package mainimport (    "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 0ch1 1ch1 2ch1 3ch1 4ch1 5ch1 6ch1 7ch1 8ch1 9finish!


package mainimport (    "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 0ch2 1ch2 2ch2 3ch2 4ch2 5ch2 6ch2 7ch2 8ch2 9finish!


package mainimport (    "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 0ch1 0ch2 1ch1 1ch2 2ch1 2ch2 3ch1 3ch2 4ch1 4ch2 5ch1 5ch2 6ch1 6ch2 7ch1 7ch2 8ch1 8ch2 9finish!

 

golang channel select