duan7664 2019-02-15 05:07
浏览 391
已采纳

fmt.go例程中的打印*主线程循环时可能不会输出

The following code as is in 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
}

prints 1 2 definitely in Windows with golang 1.11 but prints nothing definitely in Linux with golang 1.11.4. I can understand the former behavior but not the latter. Why is the go program not running non-master thread all the time?

Is there a reason behind this?

  • 写回答

1条回答 默认 最新

  • douw92892 2019-02-15 05:37
    关注

    The Go Playground runs with GOMAXPROCS=1. Try this on the playground:

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

    When you are running locally, you would perhaps have higher value of GOMAXPROCS.

    Even on playground, you can see the printing work if you deschedule the main goroutine as below by introducing a Sleep [https://play.golang.org/p/QquMPZSd6kI]:

    func main() {
        go fmt.Println("1")
        go p("2")
    
        time.Sleep(time.Second)
        for {}
     }
    

    OR

    Change the GOMAXPROCS at start:

        runtime.GOMAXPROCS(2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题