DEV Community

Discussion on: What I learned this week: running functions concurrently

Collapse
 
ineedale profile image
Alex Leonhardt

And another tweak, I noticed that still, under some circumstances, it was possible for some output to get lost, especially when sending the output received into e.g. a slice or a map instead of printing. Adding a done channel, fixes this.

    done := make(chan bool)       // done channel
    go func() {
        for m := range outputs {
            fmt.Println(m)
        }
        done <- true              // when we're done printing, send true
    }()

    wg.Wait()
    close(outputs)
    <-done                        // block and wait for done