duanfei1268 2014-03-08 04:57
浏览 30
已采纳

外出睡觉但不忙于等待

In Go, I can use time.After to time out a sleeping function, but I can't do the same to a function that is busy-waiting (or working). The following code returns timed out after one second, and then hangs.

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
}

Why doesn't the timeout fire in the second case, and what alternative do I need to use to interrupt working goroutines?

  • 写回答

1条回答 默认 最新

  • dqjcb132285 2014-03-08 06:22
    关注

    The for {} statement is an infinite loop which monopolizes a single processor. Set runtime.GOMAXPROCS to 2 or more to allow the timer to run.

    For example,

    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
    }
    

    Output (4 CPU processor):

    1
    4
    timed out
    timed out
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退