I have some problems with the following code:
package main import ( "fmt" "sync" ) // This program should go to 11, but sometimes it only prints 1 to 10. 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 } // Print prints all numbers sent on the channel. // The function returns when the channel is closed. func Print(ch <-chan int, wg sync.WaitGroup) { for n := range ch { // reads from channel until it closed fmt.Println(n) } defer wg.Done() }
I reached a dead end at the indicated location. I tried installing wg.Add(1) instead of 2, and it solves my problem. I am convinced that I am not sending a feed as an argument to the Printer function. Is there any way to do this? Otherwise, the solution to my problem replaces the go Print(ch, wg) with:
go func() { Print(ch) defer wg.Done() }
and changing the Printer function to:
func Print(ch <-chan int) { for n := range ch {
What is the best solution?
source share