golang的select与channel配合使用。它用于等待一个或者多个channel的输出。
应用场景:主goroutine等待子goroutine完成,但是子goroutine无限运行,导致主goroutine会一直等待下去。而主线程想假如超过了一定的时没有返回的话,进行超时判断然后继续运行下去。
package main
import (
"time"
"fmt"
)
var chs chan int = make(chan int,1)
func write(){
time.Sleep(3*time.Second)
chs<-1
}
func read(){
select {
case ch1:=<-chs:
fmt.Println(ch1)
return
case <-time.After(time.Second):
fmt.Println("read time out")
return
}
}
func main() {
go write()
read()
}