Go WaitGroup with goroutine

I wonder why do we run wg.Wait()ingoroutine

// This one works as expected...
func main() {
    var wg sync.WaitGroup
    for i:=0; i<5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
        }()
        time.Sleep(time.Second)
    }
    go func() {
        wg.Wait()
    }()
}

But this one never ends, waiting forever

func main() {
    var wg sync.WaitGroup
    for i:=0; i<5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
        }()
        time.Sleep(time.Second)
    }
    wg.Wait()
}

Can someone explain why I need to wait in another goroutine?

Thank!

+4
source share
1 answer

why do we need to run wg.Wait()in goroutine?

In the example you mentioned ( coop/blob/master/coop.go#L85), the wait is in goroutine to immediately return a channel that will indicate when all the other gorouts are complete. These are the main roles to start:

for _, fn := range fns {
    go func(f func()) {
        f()
        wg.Done()
    }(fn)
}

They mention completion through var wg sync.WaitGroup.
This WaitGroup command is configured to wait for the correct number of goroutines to finish:

wg.Add(len(fns))

goroutine, , , :

go func() {
    wg.Wait()
    doneSig(ch, true)
}()

.

ch := make(chan bool, 1)
...
return ch

Wait : . .

+1

All Articles