I have some issues with the following code:
package main
import (
\"fmt\"
\"sync\"
)
// This program should go to 11, but sometimes it only prints 1 to 10.
func
Well, first your actual error is that you're giving the Print
method a copy of the sync.WaitGroup
, so it doesn't call the Done()
method on the one you're Wait()
ing on.
Try this instead:
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(2)
go Print(ch, &wg)
go func() {
for i := 1; i <= 11; i++ {
ch <- i
}
close(ch)
defer wg.Done()
}()
wg.Wait() //deadlock here
}
func Print(ch <-chan int, wg *sync.WaitGroup) {
for n := range ch { // reads from channel until it's closed
fmt.Println(n)
}
defer wg.Done()
}
Now, changing your Print
method to remove the WaitGroup
of it is a generally good idea: the method doesn't need to know something is waiting for it to finish its job.