Consider this code snippet
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := new(sync.WaitGroup)
nap := func() {
wg.Add(1)
time.Sleep(2 * time.Second)
fmt.Println("nap done")
wg.Done()
}
go nap()
go nap()
go nap()
fmt.Println("nap time")
wg.Wait()
fmt.Println("all done")
}
Running such code gives expected output:
nap time
nap done
nap done
nap done
all done
Now let's ommit first standard output print before wg.Wait()
:
// fmt.Println("nap time")
wg.Wait()
fmt.Println("all done")
The output now changes to unexpected:
all done
Where expected would be:
nap done
nap done
nap done
all done
Same code on the playground does give this output without a need of omitting the stdout print.
Can you explain to me, what I am missing there?