Senior
func main() { c := make(chan int, 1000) for i := 0; i < 100; i++ { go foo(c) } sum := 0 for r := range c { sum += r } fmt.Println(sum) } func foo(c chan int) { r := rand.Int() for i := 0; i < r; i++ { c <- r } } --- func main() { c := make(chan int, 1000) var wg sync.WaitGroup wg.Add(100) for i := 0; i < 100; i++ { go func() { defer wg.Done() foo(c) }() } go func() { wg.Wait() close(c) }() sum := 0 for r := range c { sum += r } // // fmt.Println(sum) } func foo(c chan int) { r := rand.Int() for i := 0; i < r; i++ { c <- r } }
sobes.tech AI
Answer from AI
The first version of the code has a problem: the for r := range c loop will wait indefinitely because the channel c is never closed. As a result, the program will hang.
In the second version, a sync.WaitGroup is added to wait for all goroutines to finish, and after that, the channel c is closed. This allows the reading loop from the channel to exit correctly.
Key points:
- Using
sync.WaitGroupto track the completion of all goroutines. - Closing the channel after all goroutines have finished writing.
- The iteration over the channel with
for r := range cends when the channel is closed.
Example of the corrected code:
group := sync.WaitGroup{}
group.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer group.Done()
foo(c)
}()
}
go func() {
group.Wait()
close(c)
}()
sum := 0
for r := range c {
sum += r
}