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

前端 未结 4 987
悲哀的现实
悲哀的现实 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:29

    You can use sync package and take a look at waitgroups. You can take a look at a working Goplayground I set up.

    Essentially

    package main
    
    import (
        "fmt"
        "sync"
        )
    
    //Takes a reference to the wg and sleeps when work is done
    func printElo(wg *sync.WaitGroup) {
        fmt.Printf("Elo\n")
        defer wg.Done()
    }
    
    //Takes a reference to the wg and sleeps when work is done
    func printHello(wg *sync.WaitGroup) {
        fmt.Printf("Hello\n")
        defer wg.Done()
    }
    
    func main() {
        //Create a new WaitGroup
        var wg sync.WaitGroup
        fmt.Println("This will print.")
    
        for  i := 0; i < 10; i++ {
            //Add a new entry to the waitgroup
            wg.Add(1)
            //New Goroutine which takes a reference to the wg
            go printHello(&wg)
            //Add a new entry to the waitgroup
            wg.Add(1)
            //New Goroutine which takes a reference to the wg
            go printElo(&wg)
        }
        //Wait until everything is done
        wg.Wait()
    }
    

提交回复
热议问题