一、使用ctx.WithTimeout()
func doWithTimeOut1(timeout time.Duration)string{
ctx,cancel := context.WithTimeout(context.Background(),timeout)
defer cancel()
signal := make(chan int,1)
go func() {
time.Sleep(time.Second*3)
signal <- 1
}()
select {
case <-signal:
return "singal"
case <-ctx.Done():
return "timeout"
}
}
二、使用time.After()
func doWithTimeOut(timeout time.Duration)string{
out := time.After(timeout)
signal := make(chan int,1)
go func() {
time.Sleep(time.Second*3)
signal <- 1
}()
select {
case <-signal:
return "singal"
case <-out:
return "timeout"
}
}
第二种没有第一种更好,应进一步处理未完成的协程,cancel会提前结束由该上下文开启的上下文