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条)

报告相同问题?