fmt.Print 在 go 例程中 *可能* 当主线程循环时不输出

fmt.Print in go routine *may* not output when master thread is loop

以下代码如https://play.golang.org/p/X1-jZ2JcbOQ

package main
import (
        "fmt"
)
func p(s string) {
        fmt.Println(s)
}

func main() {
    go fmt.Println("1")
    go p("2")
    for {}   // infinite loop
}

在 Windows 中使用 golang 1.11 肯定打印 1 2 但在 Linux 中使用 golang 1.11.4 绝对不打印任何内容。我能理解前者的行为,但不能理解后者。为什么go程序不是一直运行非主线程?

这背后有什么原因吗?

Go Playground 以 GOMAXPROCS=1 运行。在操场上试试这个:

package main

import (
  "fmt"
  "runtime"
)

func main() {
  fmt.Println(runtime.GOMAXPROCS(0))
}

当你在 运行 本地时,你可能会有更高的 GOMAXPROCS 值。

即使在 playground 上,如果你通过引入 Sleep [https://play.golang.org/p/QquMPZSd6kI]:

来取消调度主 goroutine,你也可以看到打印工作
func main() {
    go fmt.Println("1")
    go p("2")

    time.Sleep(time.Second)
    for {}
 }

开始时更改 GOMAXPROCS:

    runtime.GOMAXPROCS(2)