协程超时处理
协程的超时处理可以在 select 中通过使用time包的After()函数来实现。
下面是 After 函数的语法:
func After(d Duration) <-chan Time
在示例中,我们在一个匿名协程中使用 time.Sleep(n * time.Second)
来模拟运行时间。
当携程运行时间大于 select 中 After 函数的超时时间,则超时的 case 匹配执行。
协程的超时处理可以在 select 中通过使用time包的After()函数来实现。
下面是 After 函数的语法:
func After(d Duration) <-chan Time
在示例中,我们在一个匿名协程中使用 time.Sleep(n * time.Second)
来模拟运行时间。
当携程运行时间大于 select 中 After 函数的超时时间,则超时的 case 匹配执行。
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
go func() {
time.Sleep(3 * time.Second)
ch <- 1
}()
select {
case <-ch:
fmt.Println("finish")
case <-time.After(time.Second * 2):
fmt.Println("timeout")
}
}
timeout