猿问

Go 在睡眠时超时,但在忙等待时不会超时

在 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

}

为什么在第二种情况下超时不触发,我需要使用什么替代方法来中断工作的 goroutines?


胡子哥哥
浏览 183回答 1
1回答

HUH函数

该for {}语句是一个无限循环,它独占一个处理器。设置runtime.GOMAXPROCS为 2 或更多以允许计时器运行。例如,package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "runtime"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; fmt.Println(runtime.GOMAXPROCS(0))&nbsp; &nbsp; runtime.GOMAXPROCS(runtime.NumCPU())&nbsp; &nbsp; fmt.Println(runtime.GOMAXPROCS(0))&nbsp; &nbsp; sleepChan := make(chan int)&nbsp; &nbsp; go sleep(sleepChan)&nbsp; &nbsp; select {&nbsp; &nbsp; case sleepResult := <-sleepChan:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(sleepResult)&nbsp; &nbsp; case <-time.After(time.Second):&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timed out")&nbsp; &nbsp; }&nbsp; &nbsp; busyChan := make(chan int)&nbsp; &nbsp; go busyWait(busyChan)&nbsp; &nbsp; select {&nbsp; &nbsp; case busyResult := <-busyChan:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(busyResult)&nbsp; &nbsp; case <-time.After(time.Second):&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timed out")&nbsp; &nbsp; }}func sleep(c chan<- int) {&nbsp; &nbsp; time.Sleep(10 * time.Second)&nbsp; &nbsp; c <- 0}func busyWait(c chan<- int) {&nbsp; &nbsp; for {&nbsp; &nbsp; }&nbsp; &nbsp; c <- 0}输出(4 CPU 处理器):14timed outtimed out
随时随地看视频慕课网APP

相关分类

Go
我要回答