Select
Go里面的Select
和Java Nio里面的模式有点类似,就是一个线程(进程/协程)同时去监听多个目标的状态。在Go里面,Select
可以让一个Goroutine同时去监听多个Channel是否到达准备状态,例子如下:
timeOut := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(time.Second * 5))
timeOut <- true
}()
timeOutNext := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(time.Second * 10))
timeOutNext <- true
}()
select {
case <-timeOut:
fmt.Println("TimeOut After 5 Seconds!")
case <-timeOutNext:
fmt.Println("TimeOut After 10 Seconds!")
}
上面代码执行时,Select
阻塞到timeOut
这个Channel收到输入时就退出了,要让Select
不退出,timeOutNext
这个Channel也有机会收到输入时,需要像下面这样写:
timeOut := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(time.Second * 5))
timeOut <- true
}()
timeOutNext := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(time.Second * 10))
timeOutNext <- true
}()
for {
select {
case <-timeOut:
fmt.Println("TimeOut After 5 Seconds!")
case <-timeOutNext:
fmt.Println("TimeOut After 10 Seconds!")
}
}