Sobes.tech
Junior — Senior

Waiting for all running goroutines to complete

livecode

Task condition

Modify the program so that the main function waits for all launched goroutines to complete before exiting.

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            printNumber(i)
        }(i)
    }

    wg.Wait()
}

func printNumber(n int) {
    time.Sleep(time.Second)
    fmt.Println(n)
}