package main
import(
"fmt"
"time"
)
func main(){
ch := make(chan string)
go HeavyOperation(ch) // 函数耗时3s, 输出timeout
// go LightOperation(ch) // 函数耗时1s, 输出light operation done
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(time.Second * 2): // 2秒之后timeout
fmt.Println("timeout")
}
}
func HeavyOperation(ch chan string){
time.Sleep(time.Second * 3)
ch <- "heavy operation done"
}
func LightOperation(ch chan string){
time.Sleep(time.Second * 1)
ch <- "light operation done"
}
select配合time.After实现超时控制
最新推荐文章于 2024-08-01 10:16:53 发布