Editor's note: this first paragraph was in response to the author's original code, which has since been edited to have markedly different semantics than the code that was originally presented.
The code example you've provided is not a particularly good example as far as demonstrating the usage of a WaitGroup
, because the program is terminated by the end of the main method rather than any co-ordination handled by the WaitGroup
. You can remove the call to wg.Done()
and that program will still compile and execute fine.
I'm happy to answer your more general questions, though.
Why are we only executing wg.Add(1) as one group to wait for instead of wg.Add(1) inside the main method for loop?
It sounds like you're asking why we don't increment wg
for each integer in the for loop. This is not really the point of WaitGroups
. A typical use case would be adding 1 for each goroutine that we're co-ordinating beyond the main goroutine. In this example, there's one other goroutine (the one handling printer
, so we only add 1 to our WaitGroup
.
A more clear version of your above example would be something like the following:
var wg sync.WaitGroup
func printer(ch chan int) {
for i := range ch {
fmt.Printf("Received %d ", i)
}
wg.Done()
}
func sender(ch chan int) {
for i := 0; i <= 10; i++ {
ch <- i
}
close(ch)
}
func main() {
c := make(chan int)
go printer(c)
go sender(c)
wg.Add(1)
fmt.Println("Waiting...")
wg.Wait()
fmt.Println("Finished")
}
In this example, we want to wait for the printer
method to have fully printed off all of its numbers we proceed with the main goroutine. So we tell our main goroutine to Wait()
until all integers have been printed, at which point we tell the main thread to proceed. Unlike your example, we close
the channel once we've entered all of our ints into it, which allows the printer
function to stop blocking on range
and to go ahead and call wg.Done
- in your original example, the printer
never stops blocking on range
and so never actually calls wg.Done
I'm really not understanding channels, period.
Hopefully the above example makes things a little more clear? I'm afraid this part of your question is a bit too broad for me to answer.