为什么从代码中调用 Setenv 不起作用?

Why Calling Setenv from code Not Working?

我有一个简单的测试项目,预计会在 运行 时打印 goroutine 调度消息。

从 Goland 配置设置 env 它有效。但它不是来自下面的代码,该应用程序不会打印调度信息。有人解释一下发生了什么吗?

func TestScheduler1() {

    var wg sync.WaitGroup
    wg.Add(10)

    for i := 0; i < 10; i++ {
        go work(&wg)
    }

    wg.Wait()
    // Wait to see the global run queue deplete.
    time.Sleep(3 * time.Second)
}

func work(wg *sync.WaitGroup) {
    time.Sleep(time.Second)

    var counter int
    for i := 0; i < 1e10; i++ {
        counter++
    }

    wg.Done()
}

初始化函数如下:

 func init()  {
    os.Setenv("GOMAXPROCS", "1")
    os.Setenv("GODEBUG", os.Getenv("GODEBUG") + "schedtrace=1000,scheddetail=1")
}

go command documentation 提到 go 检查一些环境变量:

The go command, and the tools it invokes, examine a few different environment variables.

因此,环境变量在程序启动前检查,即在构建时检查。当您从代码中设置这些变量时,程序已经运行。

它从 IDE 开始工作,因为变量是在编译之前应用的,因此代码会根据您需要的所有更改运行。