go 实现timeout功能
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
ch1 := make(chan bool)
timeout := make(chan bool)
go func() {
time.Sleep(time.Second * 5)
ch1 <- true
}()
go func() {
second := rand.Intn(10)
fmt.Println(second)
time.Sleep(time.Second * time.Duration(second))
timeout <- true
}()
//select 的 case 里的操作语句只能是【IO 操作】
select {
case <-ch1:
fmt.Print("ch1 timeout")
case <-timeout:
fmt.Println("timeout")
}
}