首页 > 解决方案 > 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,并且斐波那契函数没有任何意义让步给动画 goroutine。但是这个演示仍然有效。它在计算时显示动画。

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

标签: gogoroutine

解决方案


其中包括:编译器在每个函数调用处插入潜在的切换点,因此每个递归调用都fib(...)可以让给“微调器”goroutine。

如果您尝试在没有任何函数调用的情况下实现 fib,例如:

// note : this is a truly horrific way to compute the Fibonacci sequence,
//        don't do this at home
// simulate the "compute Fibonacci recursively" algorithm,
// but without any function call
func fib(n int) int {
    var res = 0

    var stack []int
    stack = append(stack, n)

    for len(stack) > 0 {
        // pop :
        n = stack[len(stack)-1]
        stack = stack[0 : len(stack)-1]

        if n < 2 {
            res += n
            continue
        }

        // else : push 'n-1' and 'n-2' on the stack
        stack = append(stack, n-1, n-2)
    }

    return res
}

https://play.golang.org/p/pdoAaBwyscr

你应该看到你的微调器'卡住'


推荐阅读