duannaozhao4626 2019-07-21 15:27
浏览 328
已采纳

为什么这些goroutine无法打印到控制台? [重复]

This question already has an answer here:

I can't explain the behavior of goruotines in certain cases. I try to make an easy example. This is my own file "main.go":

package main

import (
    "fmt"
)

func print1() {
    fmt.Println("print 1")
}

func print2() {
    fmt.Println("print 2")
}

func print3() {
    fmt.Println("print 3")
}

func main() {

    for i:=0; i<3; i++ {
        go print1()
    }

    for i:=0; i<3; i++ {
        go print2()
    }

    for i:=0; i<3; i++ {
        go print3()
    }

}

I would expect the 3 functions (each invoked three times in a cycle) are performed concurrently, with the result that the order of the print numbers is unpredictable. I can't understand why the program compiles and executes without any error but it doesn't print anything on the console! In practice, it is as if the function calls inside the for are not executed. If I remove the go clauses, the prints are displayed on the console. I came to the conclusion that parallel threads do not have the right to print on my console. How can I view these prints with the actual "concurrent" behavior?

</div>
  • 写回答

2条回答 默认 最新

  • dongshi1215 2019-07-21 16:49
    关注

    To get the expected result, wait for the goroutines to complete before exiting the program.

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var wg sync.WaitGroup
    
    func print1() {
        fmt.Println("print 1")
        wg.Done()
    }
    
    func print2() {
        fmt.Println("print 2")
        wg.Done()
    }
    
    func print3() {
        fmt.Println("print 3")
        wg.Done()
    }
    
    func main() {
    
        for i := 0; i < 3; i++ {
            wg.Add(1)
            go print1()
        }
    
        for i := 0; i < 3; i++ {
            wg.Add(1)
            go print2()
        }
    
        for i := 0; i < 3; i++ {
            wg.Add(1)
            go print3()
        }
    
        wg.Wait()
    }
    

    https://play.golang.org/p/mf2Uoqfdb3Z

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?