fmt.Print in go routine *may* not output when

以下代码在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

}

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


这背后有什么原因吗?


杨__羊羊
浏览 131回答 1
1回答

人到中年有点甜

Go Playground 以 GOMAXPROCS=1 运行。在操场上试试这个:package mainimport (  "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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go