轉載: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
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯繫作者獲得授權並註明出處。