1

在 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?

4

1 回答 1

6

for {}语句是一个无限循环,它垄断了单个处理器。设置runtime.GOMAXPROCS为 2 或更多以允许计时器运行。

例如,

package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {
    fmt.Println(runtime.GOMAXPROCS(0))
    runtime.GOMAXPROCS(runtime.NumCPU())
    fmt.Println(runtime.GOMAXPROCS(0))
    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
}

输出(4 CPU 处理器):

1
4
timed out
timed out
于 2014-03-08T06:22:29.250 回答