在 Go 中,我可以用来time.After
使睡眠函数超时,但我不能对忙于等待(或工作)的函数做同样的事情。下面的代码timed out
在一秒钟后返回,然后挂起。
package main
import (
"fmt"
"time"
)
func main() {
sleepChan := make(chan int)
go sleep(sleepChan)
select {
case sleepResult := <-sleepChan:
fmt.Println(sleepResult)
case <-time.After(time.Second):
fmt.Println("timed out")
}
busyChan := make(chan int)
go busyWait(busyChan)
select {
case busyResult := <-busyChan:
fmt.Println(busyResult)
case <-time.After(time.Second):
fmt.Println("timed out")
}
}
func sleep(c chan<- int) {
time.Sleep(10 * time.Second)
c <- 0
}
func busyWait(c chan<- int) {
for {
}
c <- 0
}
为什么在第二种情况下超时不会触发,我需要使用什么替代方法来中断正在工作的 goroutine?