Go 1.19中仍需使用runtime.Gosched()吗?调度异常咨询
Go 1.19中GOMAXPROCS(2)下goroutine未触发抢占式调度的问题
Go 1.15起官方说明goroutine调度无需依赖runtime.Gosched(),但我在Go 1.19中遇到异常情况:设置runtime.GOMAXPROCS(2)后,未调用runtime.Gosched()时,goroutine会先执行完一个再执行另一个,呈现出协作式调度的行为;添加runtime.Gosched()后才会出现预期的抢占式调度效果。
测试代码
import ( "fmt" "runtime" "time" ) func say(s string) { for i := 0; i < 5; i++ { fmt.Println(s) } } func main() { runtime.GOMAXPROCS(2) go say("Hello") say("World") time.Sleep(time.Second) }
实际输出(协作式调度)
Hello Hello Hello Hello Hello World World World World World
期望输出(抢占式调度)
Hello World Hello World Hello World Hello World Hello
我的CPU核心数为12,通过runtime.NumCPU()获取。
内容的提问来源于stack exchange,提问作者Huey Bui
相关产品推荐
相关产品推荐

