在休眠时节省时间,但不要在忙碌等待时间

时间:2014-03-08 04:57:55

标签: concurrency go timeout thread-sleep busy-waiting

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

1 个答案:

答案 0 :(得分: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
相关问题