Prevent the main() function from terminating before goroutines finish in Golang

前端 未结 4 983
悲哀的现实
悲哀的现实 2020-11-28 15:47

Have loook at this contrived example:

package main

import \"fmt\"

func printElo() {
    fmt.Printf(\"Elo\\n\")
}

func printHello() {
    fmt.Printf(\"Hel         


        
4条回答
  •  借酒劲吻你
    2020-11-28 16:25

    As already mentioned sync.WaitGroup is a right way in production code. But when developing for test and debug purposes you can just add select{} statement at the end or the main().

    func main(){
        go routine()
        ...
        select{}
    }
    

    main() then never returns and you would kill it with for example Ctrl-C. It isn't idiomatic, never used in production, but just very quick easy hack when developing.

提交回复
热议问题