goroutine 调度如何与 GOMAXPROCS 一起工作?
How does goroutine schedule work with 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 动画 29=]。
当我将GOMAXPROCS
设置为1
时,我认为只有一个线程可以执行goroutine,Fibonacci函数没有任何让步给动画goroutine的意义。但是这个演示仍然有效。它在计算时显示动画。
Go 在没有 goroutine 切换的情况下如何做到这一点?
除其他外:编译器在每个函数调用处插入潜在的切换点,因此对 fib(...)
的每个递归调用都可以让步给 "spinner" 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
你应该看到你的微调器 'stuck'
我对 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 动画 29=]。
当我将GOMAXPROCS
设置为1
时,我认为只有一个线程可以执行goroutine,Fibonacci函数没有任何让步给动画goroutine的意义。但是这个演示仍然有效。它在计算时显示动画。
Go 在没有 goroutine 切换的情况下如何做到这一点?
除其他外:编译器在每个函数调用处插入潜在的切换点,因此对 fib(...)
的每个递归调用都可以让步给 "spinner" 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
你应该看到你的微调器 'stuck'