You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:54:52