在 go 里面 select 会随机找一个...
官方文档地址
The Go Programming Language Specification
原文
Execution of a "select" statement proceeds in several steps:
- ...
- If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.
- ...
如果有一个或多个信道可执行,则通过统一的伪随机来选择其中一个。否则,如果存在默认情况,则选择该情况。如果没有默认情况,则 select
语句将阻塞,直到可以进行至少一种通信为止。
源码地址
可以不看代码看注释,
先进行了随机选择,然后再按随机后的顺序尝试执行,成功就出循环
Example
func test() {
c := make(chan int, 1)
c2 := make(chan string, 1)
c <- 1
c2 <- "hello"
if len(c) > 0 {
}
select {
case v := <-c:
fmt.Println("c:" + strconv.Itoa(v))
case v := <-c2:
fmt.Println("c2:" + v)
default:
fmt.Println("default")
}
}
func main() {
runtime.GOMAXPROCS(1)
for {
test()
}
}
输入结果