什么是 select?
select
语句用于在多个发送/接收信道操作中进行选择。select
语句会一直阻塞,直到发送/接收操作准备就绪。如果有多个信道操作准备完毕,select
会随机地选取其中之一执行。该语法与 switch
类似,所不同的是,这里的每个 case
语句都是信道操作。我们好好看一些代码来加深理解吧。
示例
package main
import (
"fmt"
"time"
)
func server1(ch chan string) {
time.Sleep(6 * time.Second)
ch <- "from server1"
}
func server2(ch chan string) {
time.Sleep(3 * time.Second)
ch <- "from server2"
}
func main() {
output1 := make(chan string)
output2 := make(chan string)
go server1(output1)
go server2(output2)
select {
case s1 := <-output1:
fmt.Println(s1)
case s2 := <-output2:
fmt.Println(s2)
}
}
在线运行程序[2]
在上面程序里,server1
函数(第 8 行)休眠了 6 秒,接着将文本 from server1
写入信道ch
。而 server2
函数(第 12 行)休眠了 3 秒,然后把 from server2
写入了信道 ch
。
而 main
函数在第 20 行和第 21 行,分别调用了 server1
和 server2
两个 Go 协程。
在第 22 行,程序运行到了 select
语句。select
会一直发生阻塞,除非其中有 case 准备就绪。在上述程序里,server1
协程会在 6 秒之后写入 output1
信道,而server2
协程在 3 秒之后就写入了