golang中select case用法

转载:https://www.jianshu.com/p/09f894d81dc4

先看代码:

package main

import (
    "fmt"
    "runtime"
)

func main() {
    runtime.GOMAXPROCS(1)
    int_chan := make(chan int, 1)
    string_chan := make(chan string, 1)
    int_chan <- 1
    string_chan <- "hello"
    select {
    case value := <-int_chan:
        fmt.Println(value)
    case value := <-string_chan:
        panic(value)
    }
    fmt.Println(123)
}

运行两次,结果分别为:

E:\go_study>go run 4.go
1
123

E:\go_study>go run 4.go
1
123

E:\go_study>go run 4.go
1
123

E:\go_study>go run 4.go
1
123

E:\go_study>go run 4.go
panic: hello

goroutine 1 [running]:
main.main()
        E:/go_study/4.go:18 +0x2f4
exit status 2

E:\go_study>

发现没有,如果两个case都满足条件,是伪随机选择一个执行的,而不是之前想着的从上到下依次判断哪个case能执行。

还有一点,当某个case得到执行后,就会退出select,因为打印出了 123 。

最后一点,如果没有case可以执行,则立即执行default,然后退出select



作者:舒小贱
链接:https://www.jianshu.com/p/09f894d81dc4
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/qq_33875256/article/details/89882709