golang-design / under-the-hood

📚 Go: Under The Hood | Go 语言原本 | https://golang.design/under-the-hood

Home Page:https://golang.design/under-the-hood

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ch06sched/preemption: go loop 抢占示例代码 sleep 时间延长

yangxikun opened this issue · comments

实际描述

  • 文件路径:part2runtime/ch06sched/preemption
  • 原文段落:
// 此程序在 Go 1.14 之前的版本不会输出 OK
package main
import (
	"runtime"
	"time"
)
func main() {
	for i := 0; i < runtime.GOMAXPROCS(0); i++ {
		go func() {
			for {
			}
		}()
	}
	time.Sleep(time.Millisecond)
	println("OK")
}

预期描述

// 此程序在 Go 1.14 之前的版本不会输出 OK
package main
import (
	"runtime"
	"time"
)
func main() {
	for i := 0; i < runtime.GOMAXPROCS(0); i++ {
		go func() {
			for {
			}
		}()
	}
	time.Sleep(time.Second)
	println("OK")
}

附图

image

时间延长确实是一个做法,但并不能保证 100% 复现,
一个更妥当的做法其实是强制设置 P 的数量:

package main
import (
	"runtime"
	"time"
)
func main() {
	runtime.GOMAXPROCS(1)
	go func() {
		for {
		}
	}()
	time.Sleep(time.Millisecond)
	println("OK")
}

这个例子其实在写异步抢占之前就已经准备好了,
看起来是我在写这个部分的时候忘记改掉原有的代码了 Orz

已修复,非常感谢指出文中的错误事例。