为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
杨__羊羊 2023-06-05 19:30:12
以下代码在https://play.golang.org/p/X1-jZ2JcbOQpackage mainimport (        "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程序不是一直运行非主线程?这背后有什么原因吗?
查看完整描述

1 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

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)


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信