go - 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 切换的情况下做到这一点?
解决方案
其中包括:编译器在每个函数调用处插入潜在的切换点,因此每个递归调用都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
你应该看到你的微调器'卡住'
推荐阅读
- android - 是否可以在android中添加虚拟相机?
- javascript - 调用函数 (javascript)
- azure-api-management - 使用自定义域名访问内部 VNET 的 API 管理(获取默认 IIS 页面)
- delphi - 在 Delphi 10.4 中安装和使用 DCPCrypt2
- python - 如何在每一页(所有结果)上附加数据?
- python - 为什么我不能在第二次运行中运行代码?
- scim - Curity SCIM 组端点
- autocomplete - 自定义包上的 Spyder 自动完成
- r - excel.link-将 R 数据框保存到 excel 隐藏工作表
- google-chrome - 为什么 chrome 和 firefox 的 wav 长度不同?