select语法
select {
case <-ch1:
// ...
case x := <-ch2:
// ...use x...
case ch3 <- y:
// ...
default:
// ...
}
例1:火箭点火
火箭点火倒计时10秒,如果键盘输入任意字符就打断点火,如果没有就10s后起飞。
package main
import (
"fmt"
"os"
"time"
)
func main() {
abort := make(chan struct{})
go func() {
os.Stdin.Read(make([]byte, 1))
abort <- struct{}{}
}()
fmt.Println("start countdown")
select {
case <-time.After(10 * time.Second):
case <-abort:
fmt.Println("Launch aborted!")
return
}
fmt.Println("launch")
}
例2:打印偶数
ch的buffer大小为1,会交替的为空或者满,所以只有一个case可以进行下去。
ch := make(chan int, 1)
for i := 0; i < 10; i++ {
select {
case x := <-ch:
fmt.Println(x) // "0" "2" "4" "6" "8"
case ch <- i:
}
}
非阻塞轮询channel
channel有值时,从中接收值,无值时什么都不做。这是一个非阻塞的接收操作。
select {
case <-abort:
fmt.Printf("Launch aborted!\n")
return
default:
// do nothing
}