猿问

goroutine 调度如何与 GOMAXPROCS 一起工作?

我对goroutines很困惑。


这是代码


func main() {

    // runtime.GOMAXPROCS(1)

    go spinner(100 * time.Millisecond)

    const n = 45

    fibN := fib(n) // slow

    fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN)

}


func spinner(delay time.Duration) {

    for {

        for _, r := range `-\|/` {

            fmt.Printf("\r%c", r)

            time.Sleep(delay)

        }

    }

}


func fib(x int) int {

    if x < 2 {

        return x

    }

    return fib(x-1) + fib(x-2)

}


这是一个简单的goroutine教程代码,它使用 goroutine在计算Fibonacci时显示 ASCII 动画。


当我设置GOMAXPROCS为 时1,我认为只有一个线程来执行 goroutine 并且 Fibonacci 函数没有任何意义来让步动画 goroutine。但是这个演示仍然有效。它在计算时显示动画。


Go 如何在没有 goroutine 切换的情况下做到这一点?


繁星淼淼
浏览 109回答 1
1回答

米脂

其中包括:编译器在每个函数调用处插入潜在的切换点,因此每个递归调用都fib(...)可以让给“微调器”goroutine。如果您尝试在没有任何函数调用的情况下实现 fib,例如:// note : this is a truly horrific way to compute the Fibonacci sequence,//&nbsp; &nbsp; &nbsp; &nbsp; don't do this at home// simulate the "compute Fibonacci recursively" algorithm,// but without any function callfunc fib(n int) int {&nbsp; &nbsp; var res = 0&nbsp; &nbsp; var stack []int&nbsp; &nbsp; stack = append(stack, n)&nbsp; &nbsp; for len(stack) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; // pop :&nbsp; &nbsp; &nbsp; &nbsp; n = stack[len(stack)-1]&nbsp; &nbsp; &nbsp; &nbsp; stack = stack[0 : len(stack)-1]&nbsp; &nbsp; &nbsp; &nbsp; if n < 2 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res += n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // else : push 'n-1' and 'n-2' on the stack&nbsp; &nbsp; &nbsp; &nbsp; stack = append(stack, n-1, n-2)&nbsp; &nbsp; }&nbsp; &nbsp; return res}https://play.golang.org/p/pdoAaBwyscr你应该看到你的微调器'卡住'
随时随地看视频慕课网APP

相关分类

Go
我要回答